std::vector< boost::shared_ptr< Base> > initialisieren
-
hi,
wie fügt man hier neue elemente hinzu?
std::vector< boost::shared_ptr< Base> > v; v.push_back( new Child() );oder anders?
-
std::vector< boost::shared_ptr<Base> > v; boost::shared_ptr<Base> b; v.push_back(b);
-
v.push_back( boost::shared_ptr<Base>(new Child()) );
-
Auf boost.org stehen besondere Hinweise zur Benutzung von
shared_ptr:Best Practices
A simple guideline that nearly eliminates the possibility of memory leaks is: always use a named smart pointer variable to hold the result of new. Every occurence of the new keyword in the code should have the form:shared_ptr<T> p(new Y);[...]
Avoid using unnamed shared_ptr temporaries to save typing; to see why this is dangerous, consider this example:void f(shared_ptr<int>, int); int g(); void ok() { shared_ptr<int> p(new int(2)); f(p, g()); } void bad() { f(shared_ptr<int>(new int(2)), g()); }The function ok follows the guideline to the letter, whereas bad constructs the temporary shared_ptr in place, admitting the possibility of a memory leak. Since function arguments are evaluated in unspecified order, it is possible for new int(2) to be evaluated first, g() second, and we may never get to the shared_ptr constructor if g throws an exception. See Herb Sutter's treatment (also here) of the issue for more information.
Man verliert in diesem Fall die Exceptionsicherheit.
Ausserdem gibts für Container mit Zeiger eine eigene Boost-Bibliothek, nämlich Boost.Pointer Container. Damit ist man flexibler und kann sich beim Iterieren und Zugreifen eine Indirektion sparen.