定义一个类如下:
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)
?似乎他们都调用了复制构造函数。我上面的评论是否正确?(没有编译器优化)