C++ 为什么这个构造函数被调用了两次?
我有以下代码:C++ 为什么这个构造函数被调用了两次?,c++,c++11,constructor,C++,C++11,Constructor,我有以下代码: // Example program #include <iostream> #include <string> class Hello{ public: Hello(){std::cout<<"Hello world!"<<std::endl;} }; class Base{ public: Base(const Hello &hello){ this->hello = hello
// Example program
#include <iostream>
#include <string>
class Hello{
public:
Hello(){std::cout<<"Hello world!"<<std::endl;}
};
class Base{
public:
Base(const Hello &hello){ this->hello = hello;}
private:
Hello hello;
};
class Derived : public Base{
public:
Derived(const Hello &hello) : Base(hello) {}
};
int main()
{
Hello hello;
Derived d(hello);
return 0;
}
为什么会发生这种情况 当默认构造
Base
的hello
成员时(在this->hello=hello;
赋值之前),调用它
使用成员初始值设定项列表来避免这种情况(即直接从参数hello
复制构建hello
成员):
这与移动语义无关;代码中没有移动。
Hello world!
Hello world!
Base(const Hello &hello) : hello(hello) { }