【问题标题】:Would the C++11 targeted constructor allow me to safely initialize derived class from template constructor?C++11 目标构造函数是否允许我从模板构造函数安全地初始化派生类?
【发布时间】:2019-05-06 19:30:27
【问题描述】:

我有各种从模板类栏(下)创建的对象。每个对象都有不同数据类型的数据成员(例如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;

【问题讨论】:

  • 什么是目标构造函数?我以前从未听说过。

标签: c++ c++11 templates construction


【解决方案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;
};

【讨论】:

  • 仅供参考——你是对的——坏的内存崩溃与此无关。在我的原始代码中,如果这是 bar 类型的对象,并且 defaultObject 是 bar 类型的对象的 ptr,那么尝试将整个 defaultObject 复制到正在构造的 bar 对象上是否仍然可以(this)。没有作为指针的数据成员,因此默认的复制构造函数应该可以工作。但是——如果 bar 没有从其构造函数返回,是否会调用正确对象的复制构造函数?
  • @SMGreenfield 我不确定您所说的proper copy constructor 是什么意思。当你调用operator= 时,operator= 会被调用。在我的示例中,复制构造函数被调用。
  • 我所说的“正确”的意思是——即使 bar 还没有完成构造,它将被调用的是 bar 的复制构造函数,而不仅仅是基类。
  • 使用*this = *defaultObject 将调用赋值运算符,而不是复制构造函数。
猜你喜欢
  • 2013-12-08
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多