There are many threads on Stack Overflow about the interaction between std::move and copy elision, e.g.
What are copy elision and return value optimization?
How to be confident of copy elision / return-value optimization
c++11 Return value optimization or move?
However, all of these threads do not seem to answer the question, whether one can rely on the compiler making the necessary optimizations.
This is not problematic if in the worst case we have a slight decrease in performance, but may be fatal if it conflicts correctness due to possibly duplicated destructor calls.
I have the following situation:
class ObjectContainer {
Object* obj;
public:
ObjectContainer(Object* o): obj(o) {}
~ObjectContainer() {
if (obj) delete obj;
}
ObjectContainer(ObjectContainer&& other): obj(other.obj) {
other.obj = nullptr;
}
};
ObjectContainer create_container() {
return ObjectContainer(new Object());
}
What will happen there? Is this guaranteed to work? Or can there be a situation in which the code doesn't compile or, worse, the destructor gets called twice on the same object?
As far as I understand, the compiler does not generate a default copy constructor if I declare a move constructor. Do I have to specify a copy constructor? What happens if I do? Or should I use std::move in the return statement?
I'm going to call above method like this:
void do_stuff() {
do_some_other_stuff(create_container());
}
void do_some_other_stuff(ObjectContainer const& oc) {
...
}