简体   繁体   English

继承的模板类成员在链构造函数中测试正常,但此后“丢失”

[英]Inherited template class member tests fine in chain constructor, but is “lost” thereafter

My base class, class Foo , is a template class which has the following constructor: 我的基类class Foo是一个模板类,它具有以下构造函数:

//Declarations
template <class T>
class Foo
{
public:
    Foo::Foo(std::string& root);
    MemberClass obj;
}

template <class T>
Foo<T>::Foo(std::string& root)
{
    MemberClass obj(root); // initialize the member object
    obj.getRoot(); // Prints the string
    // ...
}

It has a child class, which is constructed like so: 它有一个子类,其构造如下:

template <class T>
Bar<T>::Bar(std::string& root)
    : Foo<T>(root)
{
    //...
}

template<class T>
void
Bar<T>::accessObj()
{
    this->obj.getRoot();
    // Prints the empty string
}

This gives unexpected behaviour, even though no errors are generated. 即使没有错误生成,这也会带来意外的行为。 In this case, getRoot() will return the empty string. 在这种情况下, getRoot()将返回空字符串。

I have tested this by altering the Foo constructor like so: 我已经通过更改Foo构造函数进行了测试,如下所示:

{
    MemberClass obj(root);
    std::cout << &obj << std::endl;
}

and the Bar constructor like so: Bar构造函数是这样的:

//...
    : Foo<T>(root)
{
    std::cout << &this->obj << std::endl;
}

The output gives two different locations in memory, which is totally blowing my mind. 输出给出了内存中的两个不同位置,这完全让我震惊。 Why is this the case? 为什么会这样呢? How do I fix it? 我如何解决它?

Your constructor might better look like this: 您的构造函数最好如下所示:

template <class T>
Foo<T>::Foo(std::string& root)
    : obj(root) // initialize the member object
{
    obj.getRoot(); // Prints the string
    // ...
}

Before, you were constructing a temporary obj in your Foo constructor and throwing it away, never initializing your member variable at all. 以前,您是在Foo构造函数中构造一个临时obj并将其丢弃,根本没有初始化您的成员变量。

If you're using GCC, the option -Wshadow might have helped catch this mistake. 如果您使用的是GCC,则-Wshadow选项可能有助于捕获此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM