【发布时间】:2019-03-10 17:28:16
【问题描述】:
class Entity
{
public:
int a;
Entity(int t)
:a(t)
{
std::cout << "Constructor !" << std::endl;
}
~Entity()
{
std::cout << "Destructor !" << std::endl;
}
Entity(Entity& o)
{
std::cout << "Copied !" << std::endl;
this->a = o.a;
}
};
Entity hi()
{
Entity oi(3);
return oi;
}
int main()
{
{
Entity o(1);
o = hi();
}
std::cin.get();
}
输出:
构造函数!
构造函数!
复制!
析构函数!
析构函数!
析构函数!
我创建了两个对象并复制了一个,所以三个构造函数和三个析构函数。
【问题讨论】:
-
Entity(Entity& o)也是一个构造函数。 -
您需要检测复制构造函数。此外,三法则 - 你可能也想要一个赋值运算符。
-
对不起。我不明白。
-
是的。我知道复制构造函数
-
@Bubeshp
return oi;-- 这是做什么的?除非调用 RVO,否则会创建一个副本。仅仅因为 you 没有显式创建对象并不意味着编译器没有创建对象。
标签: c++ constructor destructor object-lifetime