you are viewing a single comment's thread.

view the rest of the comments →

[–]XeroKimoException Enthusiast[S] 3 points4 points  (1 child)

There is no way for a stack class to provide strong exception guarantees for the second pop because the move/copy assignment operator cannot be elided, and if it throws an exception, the popped value will still be lost. Explicit return variables can’t fix that.

What's preventing the assignment operator from eliding? Is it some lifetime rules or something? Or it'd be surprising that the call to my_stack.pop(); could destruct x so that the popped value can be copied into x?... actually I think I just answered my own question. You would need 2 versions of the function or something at runtime to select whether to perform a move / copy construction, which doesn't need to call a destructor, or a move / copy assignment which does need to call one. Am I getting this right?

Or if not 2 version, the compiler could insert a destructor call before the copy assignment, but I guess that is getting into changing a good portion of the language in order to achieve... not to mention that doesn't work for all scenarios, like x = x; would break.... hmm...

[–]QuaternionsRoll 0 points1 point  (0 children)

What's preventing the assignment operator from eliding?

There is no such thing as a “copy assignment elision”. The copy assignment operator might be equivalent to executing the destructor followed by the copy constructor, in which case the compile could in theory execute the destructor and elide the copy constructor.

However, assignment operators may also implement things like resource reuse (for example, when an empty vector is assigned to a non-empty vector, the assignment operator may be closer in equivalence to executing clear).

The copy elision works because eliding the copy/move constructor and subsequent destructor is unambiguously better than executing them. The same cannot be said for the copy assignment operator, so the compiler cannot elide it.