阐明我对复制初始化和直接初始化的见解
To Clarify my insights to copy initialization and direct initialization
定义一个class如下:
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 = a1
和A a2(a1)
有什么区别呢?似乎他们都调用了复制构造函数。我上面的评论是否正确? (假设没有编译器优化)
有区别direct-initialization and copy-initialization:
Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.
因此,如果您创建复制构造函数 explicit
,那么 A a3 = a1
将不起作用;而 A a2(a1)
仍然可以正常工作。
定义一个class如下:
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 = a1
和A a2(a1)
有什么区别呢?似乎他们都调用了复制构造函数。我上面的评论是否正确? (假设没有编译器优化)
有区别direct-initialization and copy-initialization:
Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.
因此,如果您创建复制构造函数 explicit
,那么 A a3 = a1
将不起作用;而 A a2(a1)
仍然可以正常工作。