简体   繁体   中英

Why is copy-constructor not called in this case?

I encountered a code snippet and thought that it would call copy-constructor but in contrast , it simply called normal constructor . Below is the code

#include <iostream>
using namespace std;
class B
{
    public:    
    B(const char* str = "\0")
    {
        cout << "Constructor called" << endl;
    }    
    B(const B &b)
    {
        cout << "Copy constructor called" << endl;
    } 
};
int main()
{  
    B ob = "copy me"; 
    return 0;
}

What you've discovered that B ob = "copy me"; notionally creates a B from the literal and then copy constructs ob , but that the compiler is allowed to elide the copy and construct directory into ob . g++ even elides the copy with no optimization enabled at all.

You can observe that this is the case by making your copy constructor private: The code will fail to compile even though the compiler won't actually use the copy constructor (the standard requires that copy constructors be accessible even when the call is elided).

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