C ++ CRTP初始化 [英] C++ CRTP initialization
问题描述
我遇到了运行以下程序的段错误
#include< iostream>
#include< vector>
模板< typename Derived>
结构CRTPBase {
CRTPBase(){
func();
}
void func(){
static_cast< Derived *>(this)-> _func();
}
};
结构CRTPChild:CRTPBase< CRTPChild> {
使用CRTPBase< CRTPChild> :: CRTPBase;
void _func(){
vec.resize(10);
vec [0] = 2;
}
std :: vector< int> vec;
};
int main()
{
CRTPChild obj;
std :: cout<< obj.vec [0]<< std :: endl;
}
当我替换 vec
成员类型为 int
的成员,则不再进行段错误。为什么?
您的代码具有未定义的行为。问题来自初始化顺序;对于派生类 CRTPChild
,首先调用基类 CRTPBase< CRTPChild>
的构造函数。 CRTPChild
的成员 vec
被初始化。从基类的构造函数调用 _func
时,根本不会初始化 vec
。
2)然后,直接基类按从左到右的顺序初始化为
,它们出现在此类的基本说明符列表中
3)然后,以类定义中的
声明的顺序初始化非静态数据成员。
将类型更改为 int
仍为 UB 。 UB意味着一切皆有可能,它可能导致段错误或可能不会。
i ran into a segfault running the following program
#include <iostream>
#include <vector>
template <typename Derived>
struct CRTPBase {
CRTPBase() {
func();
}
void func() {
static_cast<Derived*>(this)->_func();
}
};
struct CRTPChild : CRTPBase<CRTPChild>{
using CRTPBase<CRTPChild>::CRTPBase;
void _func(){
vec.resize(10);
vec[0] = 2;
}
std::vector<int> vec;
};
int main()
{
CRTPChild obj;
std::cout << obj.vec[0] << std::endl;
}
When i replace vec
with a member of type int
it doesn't segfault anymore. Why?
Your code has undefined behavior. The problem comes from the order of the initialization; for the derived class CRTPChild
, the constructor of the base class CRTPBase<CRTPChild>
is invoked firstly, after that the data member vec
of CRTPChild
get initialized. When _func
is invoked (from the constructor of the base class) vec
is not initialized at all.
2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list
3) Then, non-static data members are initialized in order of declaration in the class definition.
Changing the type to int
it's still UB. UB means anything is possible, it might lead to segfault or might not.
这篇关于C ++ CRTP初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!