C++11 目标构造函数是否允许我从模板构造函数安全地初始化派生 class?

Would the C++11 targeted constructor allow me to safely initialize derived class from template constructor?

我有从模板 class 栏创建的各种对象(如下)。每个对象都有一个不同数据类型的数据成员(例如std::string、bool、int等)

我在静态数组中有一组 derived/templated 类型的当前默认值,这些默认值是通过 new 构造的。

我想在构造函数中初始化对象,而不需要单独的初始化步骤。

我可以确定我从静态数组中检索的默认对象类型绝对是相同的模板类型。

我想我 运行 遇到以下问题:在构造函数完成之前,对象 bar 并不是真正的对象 bar 类型?在 C++11 中有没有办法使用目标或委托构造函数来解决这个问题?

class foo
{
public:
    foo(int index) : fMyIndex(index) { }

protected:
    int fMyIndex;

};

template<class T>
class bar : public foo
{
public:
    // This constructor takes the integer prefIndex, then constructs
    // the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
    //
    bar(int index) : foo(index)
    {
        // get the most current version of the in-memory data.  defaultObject is a pointer to a "BarString"
        foo* defaultObject = static_cast<bar*>(GetDefaultData(fMyIndex));
        if (defaultObject) {
            // bad memory access!
            *this = *defaultObject;
        }
    }

private:
    T fMyData;

};


typedef bar<std::string> BarString;
typedef bar<int> BarInt;
typedef bar<bool> BarBool;

当然你可以使用委托构造函数,但我想知道为什么你在那里得到一个错误的内存访问:

// bad memory access!
*this = *defaultObject;

据我所知,这没有错。


但实际上您可以使用委托构造函数,只要您不像您那样直接调用基本构造函数即可。相反,bar 的复制构造函数将为其基础调用适当的构造函数。

template<class T>
struct bar : foo {
    // This constructor takes the integer prefIndex, then constructs
    // the object based on current in-memory settings, which it obtains from a static array via static GetDefaultData;
    bar(int index) : bar(*static_cast<bar*>(GetDefaultData(index))) {}

private:
    T fMyData;
};