我有以下简单的代码:
#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
在没有触摸对象时调用Base
构造函数是否安全?我的意思是,当没有这样的线时,只是触摸对象。Derived::foo
Derived
a = 4
Base
2)如果我运行发布的代码,它确实有效,尽管我正在触及a
当时不应该存在的代码。能保证工作吗?(我在 Ideone 上的 VS2013、VS2010 和GCC 4.8.1 上对其进行了测试)