gpt4 book ai didi

c++ - 阐明我对复制初始化和直接初始化的见解

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:16 26 4
gpt4 key购买 nike

定义一个类如下:

class A {
public:
A(): s("") {} //default constructor
A(const char* pStr): s(pStr) {} //constructor with parameter
A(const A& a) : s(a.s) {} //copy constructor
~A() {} //destructor
private:
std::string s;
};

下面的代码将执行直接初始化:

A a1("Hello!");   //direct initialization by calling constructor with parameter
A a2(a1); //direct initialization by calling copy constructor

接下来会执行复制初始化:

A a3 = a1;  
A a4 = "Hello!";

据我了解,A a4 = "Hello" 等同于:

//create a temporary object first, then "copy" this temporary object into a4 by calling copy constructor    
A temp("Hello!");
A a4(temp);

那么 A a3 = a1A a2(a1) 有什么区别呢?似乎他们都调用了复制构造函数。我上面的评论是否正确? (没有编译器优化)

最佳答案

direct-initialization 之间有区别和 copy-initialization :

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

因此,如果您使复制构造函数显式,则A a3 = a1 将不起作用;而 A a2(a1) 仍然可以正常工作。

关于c++ - 阐明我对复制初始化和直接初始化的见解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com