【发布时间】:2014-03-27 08:45:10
【问题描述】:
我有以下简单代码:
#include <iostream>
#include <vector>
template <class Derived>
struct Base
{
Base()
{
static_cast<Derived*>(this)->foo();
}
std::vector<int> m_ints;
};
struct Derived : Base<Derived>
{
Derived() : Base()
{
std::cout << a;
}
void foo()
{
m_ints.push_back(37);
a = 4;
}
int a;
};
int main()
{
Derived d;
return 0;
}
我知道创建对象时调用构造函数的顺序。构造函数是从“最基础 -> 向下”调用的。所以在 Base 构造函数中,Derived 对象没有完全构造。
1) 当Derived::foo 不接触Derived 对象时,在Base 构造函数中调用Derived::foo 是否安全?我的意思是,当没有a = 4 这样的行时,只需触摸Base 对象。
2) 如果我运行发布的代码,它确实有效,尽管我正在触摸当时不应该存在的a。能保证工作吗? (我在VS2013、VS2010和GCC 4.8.1 on Ideone上测试过)
【问题讨论】:
-
你想做什么?
-
看看this
标签: c++ crtp static-polymorphism