我有这段代码,我正在尝试了解编译器的工作原理:
#include <iostream>
using namespace std;
class Block
{
int data;
public:
Block(int i = 10)
: data(i)
{
cout << "I just created a Block " << endl;
}
~Block()
{
cout << "I will destroy a Block with " << data << endl;
}
void inc()
{
data++;
}
};
class A
{
Block& block1;
Block block2;
public:
A(Block& blk)
: block1(blk)
, block2(blk)
{
cout << "I just created an A " << endl;
}
A(const A& a)
: block1(a.block1)
, block2(a.block2)
{
cout << "I just created an A by copying but I will also do bad things" << endl;
block1.inc();
block2.inc();
}
~A()
{
cout << "I will destroy an A " << endl;
}
void inc()
{
block1.inc();
block2.inc();
}
};
class Fat
{
A a;
A& ra;
A* pa;
public:
Fat(A& da)
: a(da)
, ra(da)
{
pa = new A(da);
cout << "Fat just created !" << endl;
}
~Fat()
{
delete pa;
cout << "Fat to be destroyed !" << endl;
}
void inc()
{
a.inc();
ra.inc();
pa->inc();
}
};
int main()
{
Block block;
A a(block);
Fat fat(a);
fat.inc();
return 0;
}
当它创建一个对象时,是创建一个新的 block 还是使用现有的 block ? 为什么不运行 block 的构造函数?
程序的输出是:
I just created a Block
I just created an A
I just created an A by copying but I will also do bad things
I just created an A by copying but I will also do bad things
Fat just created !
I will destroy an A
I will destroy a Block with 12
Fat to be destroyed !
I will destroy an A
I will destroy a Block with 12
I will destroy an A
I will destroy a Block with 11
I will destroy a Block with 15
最佳答案
您可以使用更简单的代码来证明这一点。
#include <iostream>
class Noisy
{
public:
Noisy()
{ std::cout << "Noisy default construct\n"; }
~Noisy()
{ std::cout << "Noisy destroy\n"; }
};
int main()
{
Noisy noisy1;
Noisy noisy2(noisy1);
}
输出
Noisy default construct Noisy destroy Noisy destroy
Notice that, apparently, only one object was constructed, but two were destroyed. The reason for this apparent inconsistency is because we are not logging all or our constructors. There is an implicitly generated copy constructor, which we are using to construct noisy2
in this line here:
Noisy noisy2(noisy1);
如果我们自己定义拷贝构造函数,
#include <iostream>
class Noisy
{
public:
Noisy()
{ std::cout << "Noisy default construct\n"; }
Noisy(Noisy const&)
{ std::cout << "Noisy copy construct\n"; }
~Noisy()
{ std::cout << "Noisy destroy\n"; }
};
int main()
{
Noisy noisy1;
Noisy noisy2(noisy1);
}
输出:
Noisy default construct Noisy copy construct Noisy destroy Noisy destroy
可以看到构造了两个对象,只是构造函数不同而已。如果您对各种类执行此操作,您应该会看到类似的结果。您的引用不会被记录,无论是构造函数还是析构函数,因为它们不是对象。
关于c++ - 构造函数在必须创建其他类的新对象时如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319035/