我有一个类层次结构,其中我知道给定的类 (B) 将始终派生到第二个类 (D)。在 B 的构造函数中,如果我确定在整个构造完成之前没有人会尝试使用它,那么将 this
指针静态转换为 D* 是否安全?在我的例子中,我想将对象的引用传递给另一个类 (A)。
struct A
{
D & d_;
A(D & d) : d_(d) {}
};
struct D; //forward declaration
struct B
{
A a;
B() : a(std::static_cast<D&>(*this)) {}
};
struct D : public B
{};
这段代码安全吗?
最佳答案
我没有找到任何相关信息。我很难找到你的代码在安全的情况下不安全的原因:
struct B
{
A a;
B(D& d) : a(d) {}
};
struct D : public B
{
D() : B(*this) {}
};
但我可能仍会使用此处显示的表格。
关于c++ - 在施工期间向下倾斜是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1193134/