exception-safe

Is it safe to push_back 'dynamically allocated object' to vector?

て烟熏妆下的殇ゞ 提交于 2019-12-18 04:19:06
问题 Whenever I need to add dynamically allocated object into a vector I've been doing that the following way: class Foo { ... }; vector<Foo*> v; v.push_back(new Foo); // do stuff with Foo in v // delete all Foo in v It just worked and many others seem to do the same thing. Today, I learned vector::push_back can throw an exception. That means the code above is not exception safe. :-( So I came up with a solution: class Foo { ... }; vector<Foo*> v; auto_ptr<Foo> p(new Foo); v.push_back(p.get()); p

Can a stack have an exception safe method for returning and removing the top element with move semantics?

家住魔仙堡 提交于 2019-12-10 12:53:56
问题 In an answer to a question about std::stack::pop() I claimed that the reason pop does not return the value is for exception safety reason (what happens if the copy constructor throws). @Konrad commented that now with move semantics this is no longer relevant. Is this true? AFAIK, move constructors can throw, but perhaps with noexcept it can still be achieved. For bonus points what thread safety guarantees can this operation supply? 回答1: Of course, not every type is move-enabled and C++0x even

Is it safe to push_back 'dynamically allocated object' to vector?

允我心安 提交于 2019-11-29 04:35:57
Whenever I need to add dynamically allocated object into a vector I've been doing that the following way: class Foo { ... }; vector<Foo*> v; v.push_back(new Foo); // do stuff with Foo in v // delete all Foo in v It just worked and many others seem to do the same thing. Today, I learned vector::push_back can throw an exception. That means the code above is not exception safe. :-( So I came up with a solution: class Foo { ... }; vector<Foo*> v; auto_ptr<Foo> p(new Foo); v.push_back(p.get()); p.release(); // do stuff with Foo in v // delete all Foo in v But the problem is that the new way is