简体   繁体   English

为什么在这种情况下不调用复制构造函数?

[英]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 . 我遇到了一个代码片段,以为它会调用copy-constructor,但是相比之下,它只是简单地称为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"; 您发现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 . 从字面上名义上创建一个B ,然后复制构造ob ,但是允许编译器将拷贝和构造目录移到ob g++ even elides the copy with no optimization enabled at all. g ++甚至消除了该副本,而没有启用任何优化。

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). 您可以通过将复制构造函数设为私有来观察这种情况:即使编译器实际上不会使用复制构造函数,代码也将无法编译(标准要求即使调用被删除,复制构造函数也可以访问)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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