|
|
1: creating countOne 2: Constructor called 3: 4: creating countTwo using function copy() 5: Copy constructor called 6: address of temp: 0x22fefe 7: address of countTwo: 0x22fefe 8: 9: countOne and countTwo are going out of scope 10: Destructor called 11: Destructor called |
keskiverto wrote: |
---|
Your compiler probably does optimization. |
-fno-elide-constructors The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases. |
I think maybe due to the fact that he didnt overload the assignment operator |
Counter countTwo(copy(countOne));
and Counter temp(copied);
to avoid the assignment operator, yet the output does not change.The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. |
|
|
4: creating countTwo using function copy() 5: Copy constructor called (This is for passing countOne by value right?) 6: address of copied: 0x22feff 7: Copy constructor called (a copy is made this time) 8: Destructor called (Is it for the parameter or the object just returned?) 9: address of countTwo: 0x22fefd |
The illusionist mirage wrote: |
---|
I think maybe due to the fact that he didnt overload the assignment operator, a bitwise copy is performed and so temp & countTwo share the same address |
Counter temp = copied;
Counter temp(copied);
Counter temp = copied;
because the copy constructor has an observable side effect. an implementation may omit a copy operation resulting from a return statement, even if the copy constructor has side effects. http://en.wikipedia.org/wiki/Return_value_optimization |
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies): — in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value <other clauses elided for brevity> |
|
|
|
|