0

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

我在一个静态数组中有一组当前默认值,每个派生/模板化类型都是通过 new 构造的。

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

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

我想我遇到的问题是,在构造函数完成之前,对象栏并不是真正的对象栏类型?在 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;
4

1 回答 1

1

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

// 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;
};
于 2019-05-06T20:03:27.363 回答