0

Here is the class with verbose constructors:

class A
{
public:
    A() : _a(-1) { std::cerr << "ctor" << _a << std::endl; }
    A(int a_) : _a(a_) {  std::cerr << "ctor2 "<< _a << std::endl; }
    ~A() { std::cerr << "dtor "<< _a << std::endl; }
    A(const A&) { std::cerr << "cctor "<< _a << std::endl;}
    A(A &&) { std::cerr <<"mctor " << _a << std::endl; }
private:
    int _a;
};

Why only one constructor is callet in this example:

int main(int,char **)
{
    A a(A(1));
}

No move nor copy constructor is called. Is it auto-optimized by the compiler?

user2449761
  • 1,169
  • 13
  • 25
  • 3
    Yes, it is called copy elision. Most modern compilers do this, although not required by the standard. Compile (if using g++/clang++) with -fno-elide-constructors and you'll see all constructors in all their glory. – vsoftco Feb 20 '15 at 16:09
  • thanks, this is wierd because constructors can have side effects... ;/ – user2449761 Feb 21 '15 at 21:47
  • 1
    There are some rules under which conditions copy elision takes place. If there are no visible side effects then copy elision is performed. Note that even having `std::cout << "something";` in your constructor still makes it eligible for copy elision, as it doesn't have a side effect on the logic of the program. Best to read what exactly the rules are from the standard. – vsoftco Feb 21 '15 at 22:47

0 Answers0