Home > Mobile >  Copy constructor implicitly called?
Copy constructor implicitly called?

Time:05-02

I have the following class with both a normal constructor and copy constructor defined.

#include <iostream>

class Bla
{
public:
    Bla()
    {
        std::cout << "Normal Constructor Called\n";
    }

    Bla(const Bla& other)
    {
        std::cout << "Copy Constructor Called\n";
    }

};

int main() 
{
    Bla a = Bla(); // prints Normal Constructor
}

In the main function, it prints the normal constructor as I expected and only the normal constructor. However, if I make the copy constructor a private member of the class, the compiler gives me the error

error: ‘Bla::Bla(const Bla&)’ is private within this context

From the looks of it, it looks like the copy constructor was called, but I do not see anything being printed from it. Is the copy constructor being implicitly called? What's going on here?

CodePudding user response:

Before C 17, the copy operation might be elided but the copy constructor still needs to be present and accessible.

This is an optimization: even when it takes place and the copy/move (since C 11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:

Since C 17 there's no such issue because of mandatory copy elision.

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

  • Related