【发布时间】:2021-12-20 14:08:43
【问题描述】:
我运行下面的代码将对象的父部分分配给子对象。 但正如内联所描述的,c 风格的向下转型表现出一些意想不到的事情。 那里发生了什么?请参考下面的评论。
struct A {
public:
int i{};
A() { std::cout<<"A constructor called\r\n"; }
~A() { std::cout<<"A destructor called\r\n"; }
};
struct B : public A {
B() { std::cout<<"B constructor called\r\n"; }
~B() { std::cout<<"B destructor called\r\n"; }
};
A a{};
B b{};
a.i = 1;
(A)b = a; // this code no effect and surprisingly the destructor of A is called.
// there was no compiler warning (g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0)
std::cout<<a.i<<std::endl;
std::cout<<b.i<<std::endl;
A& ra = b;
ra = a; // A portion of B is initialized as expected
std::cout<<b.i<<std::endl;
此代码打印为
构造函数调用
一个名为
的构造函数
B 构造函数调用
一个名为
1
0
1
调用 B 析构函数
一个名为
的析构函数
一个名为
【问题讨论】:
-
(A)b导致一个新的A被复制构造查看实时 - godbolt.org/z/ox11h76sd 。注意this的值被输出以启用跟踪对象的创建/销毁。为了清楚起见,我还注释掉了作业。 -
好吧,对象的 c 风格向下转换会导致复制构造。这就是为什么不调用 A 的构造函数的原因。那么这是 c++ 行为吗?
标签: c++ class struct variable-assignment downcast