【发布时间】:2018-11-06 01:02:18
【问题描述】:
我目前正在使用 CRTP,并且遇到了派生类中的成员变量被损坏的问题,即具有垃圾值(目前有 4 级多态性,最顶层的基类称为“A " 和最底层的派生类 "D")。
以下是一些显示此问题示例的代码:
//A.hpp
template <class TB>
class A {
public:
A();
void CRTP_func();
};
template <class TB>
A<TB>::A() {
std::cout << "A constructor called!" << std::endl;
}
template<class TB>
void A<TB>::CRTP_func() {
std::cout << "CRTP_index called in A" << std::endl;
static_cast<TB*>(this)->CRTP_func2();
}
//B.hpp
#include "A.hpp"
#include <vector>
template<class TC>
class B : public A<B<TC>>
{
public:
B();
void CRTP_func2();
};
template<class TC>
B<TC>::B() {
std::cout << "B constructor called!" << std::endl;
}
template<class TC>
void B<TC>::CRTP_func2() {
std::cout << "CRTP_func called in B" << std::endl;
static_cast<TC*>(this)->CRTP_func3();
}
//C.hpp
#include "B.hpp"
template<class TD>
class C : B<C<TD>> {
public:
C();
void CRTP_func3();
int x;
};
template<class TD>
C<TD>::C() {
std::cout << "C constructor called" << std::endl;
}
template<class TD>
void C<TD>::CRTP_func3() {
std::cout << "CRTP_index3 called in C" << std::endl;
static_cast<TD*>(this)->CRTP_func4();
}
//D.hpp
#include "C.hpp"
class D : C<D> {
public:
D();
bool onInit();
void CRTP_func4();
C<D> top;
int y = 0;
};
D::D() {
std::cout << "D constructor called!" << std::endl;
}
bool D::onInit() {
std::cout << "D onInit called!" << std::endl;
y = 5;
return true;
}
void D::CRTP_func4() {
std::cout << y << std::endl;
std::cout << "CRTP_index4 called in D! " << std::endl;
}
//main.hpp
int main {
D * D_ptr = new D();
D_ptr->onInit();
D_ptr->top.CRTP_func3();
return 0;
}
如您所见,A 是基类,而 D 是派生类:
A<B<C<D>>>
这个程序的输出如下:
A constructor called!
B constructor called!
C constructor called
A constructor called!
B constructor called!
C constructor called
D constructor called!
D onInit called!
CRTP_index3 called in C
-33686019
CRTP_index4 called in D!
值 -33686019 打印在 D.hpp 中,其中打印值 y 并在初始化时设置为 5。经过一番挖掘,我检查了 main.cpp 中的值,即使在进行了这些 CRTP 调用之后,它也设置为 5,但打印出一个垃圾值。
经过更多调试后,我意识到删除该行
int x;
in B.hpp 解决了这个问题,所以我认为这个问题与一些错位有关,但我不确定为什么会发生这种情况。有谁知道为什么会发生这种情况或如何解决?
抱歉,帖子太长,代码模棱两可,为了帖子,我尽量去除大部分复杂性并尽可能简化代码。
更新:
感谢下面的 cmets,我找到了解决问题的方法。除了使用D::top,更好的方法是在主文件中创建一个指针,如下所示:
C<D> * C_ptr = static_cast<C<D>*>(D_ptr);
然后从那里调用CRTP_func3():
C_ptr->CRTP_func3();
这按预期工作。
【问题讨论】:
标签: c++ polymorphism crtp