c++ - Why the copy constructor is not called? -


in code:

#include <iostream>  using std::cout;  class foo {     public:         foo(): egg(0) {}         foo(const foo& other): egg(1) {}          int egg; };  foo bar() {     foo baz;     baz.egg = 3;     return baz; }  int main(void) {     foo spam(bar());     cout << spam.egg;     return 0; } 

the output 3, while expected 1.

that means copy constructor not called in line foo spam(bar()).

i guess it's because bar function doesn't return reference.

could please explain what's going on @ initialization of spam?

i apologize in advance if that's dumb question.

thanks!

copy/move elision allowed exception so-called "as-if" rule, constrains kinds of transformations (e.g. optimizations) compiler allowed perform on program.

the rule intended allow compilers perform optimization wish long transformed program work "as if" original one. however, there 1 important exception.

per paragraph 12.8/31 of c++11 standard:

when criteria met, implementation allowed omit copy/move construction of class object, even if constructor selected copy/move operation and/or destructor object have side effects. [...] elision of copy/move operations, called copy elision, permitted in following circumstances (which may combined eliminate multiple copies):

  • in return statement in function class return type, when expression name of non-volatile automatic object (other function or catch-clause parameter) same cv-unqualified type function return type, copy/move operation can omitted constructing automatic object directly function’s return value

[...]

  • when temporary class object has not been bound reference (12.2) copied/moved class object same cv-unqualified type, copy/move operation can omitted constructing temporary object directly target of omitted copy/move

[...]

in other words, should never rely on copy constructor or move constructor being called or not being called in cases provisions of 12.8/31 apply.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -