The following code was compiled and run in Visual Studio 2012 Express for Windows Desktop as a training exercise.
#include <cstdio> class X { public: X() { printf("default constructed\n"); } ~X() { printf("destructed\n");} X(const X&) { printf("copy constructed\n"); } X(X&&) { printf("move constructed\n"); } X & operator= (const X &) { printf("copy assignment operator\n"); } }; XA() { X x; return x; } int main() { { A(); } std::getchar(); }
When compiling with the compiler disabled (/ Od), the resulting output indicates that the destructor is called twice. This is a problem in which only one object is built. Why is the destructor called twice? Wouldn't it be a problem if the class managed its own resources?
default constructed move constructed destructed destructed <<< Unexpected call
I tried a couple of experiments to try to explain the solution, but in the end it did not lead to any useful explanations.
Experiment 1. When the same code is compiled with optimizations enabled (/ O1 or / O 2), the resulting output:
default constructed destructed
which indicates that Optimization with the lowest return value rejected the call to the move constructor and masked the main problem.
Experiment 2: Turn off optimization and comment on the move constructor. The output was what I expected.
default constructed copy constructed destructed destructed
c ++ c ++ 11 move-semantics visual-c ++ visual-studio-2012
Phillip ngan
source share