简体   繁体   中英

Copy constructor implicitly called?

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM