简体   繁体   English

为什么我不能添加shared_ptr <Derived> 到地图 <key_type,shared_ptr<Base> &gt;在此代码中?

[英]Why can't I add a shared_ptr<Derived> to a map<key_type,shared_ptr<Base>> in this code?

I'd like to add a shared_ptr<derived> to a map with shared_ptr<base> values (as below http://ideone.com/hd68yc ) but it fails (we reach EXIT_FAILURE ): 我想将shared_ptr<derived>添加到具有shared_ptr<base>值的地图(如下http://ideone.com/hd68yc ),但是失败(我们到达EXIT_FAILURE ):

#include <iostream>
#include <map>
#include <memory>
using namespace std;

class base{
    public:
        base(const int& s = 1):setting{s}{};
        int setting;
};
class derived : public base{
    public:
        derived(const int& s):setting{s}{};
        int setting;
};

int main() {
    map<string,shared_ptr<base>> m_s;
    m_s.insert(make_pair("Name",make_shared<derived>(4)));
    // None of these worked either...
    //m_s.emplace("Name",make_shared<derived>(4));
    //m_s["Name"] = make_shared<derived>(4);

    if(4 == m_s.at("Name")->setting){
        return EXIT_SUCCESS;
    }else{
        cout << "setting is " << m_s.at("Name")->setting << " when 4 expected";
        return EXIT_FAILURE;
    }
}

You cannot initialize base class member in constructor initialization list, but you can call proper base class constructor: 您不能在构造函数初始化列表中初始化基类成员,但是可以调用适当的基类构造函数:

class derived : public base{
    public:
        derived(const int& s):base{s}{};
};

Your naive "fix" to put member setting into derive class does not fix the issue, but hides it, allow code to compile, but breaking the logic. 将成员setting放入派生类的幼稚“修复”并不能解决问题,而是将其隐藏,允许代码进行编译,但是破坏了逻辑。

For a start, the derived class contains an extra setting member. 首先,派生类包含一个额外的setting成员。 Getting rid of that revealed that I can't use the derived(const int& s):setting{s}{}; 摆脱这一点表明我不能使用derived(const int& s):setting{s}{}; ctor syntax since it refers to a setting member that is inherited. ctor语法,因为它引用继承的setting成员。

In the end, using the following fixed my problem: 最后,使用以下命令解决了我的问题:

class correct_derived : public base{
    public:
        correct_derived(const int& s){
            setting = s;
        }
};
m_s.insert(make_pair("Name",make_shared<derived>(4)));

if(4 == m_s.at("Name")->setting) {

As far as I can tell you store a Pointer in a map and then compare it to an int (4). 据我所知,您将Pointer存储在地图中,然后将其与int(4)进行比较。 You would have to de-reference the stored shared pointer to get its value which you then can compare to '4'. 您必须取消引用存储的共享指针才能获取其值,然后可以将其与“ 4”进行比较。 That might be the reason you end up at EXIT_FAILURE. 这可能就是您最终获得EXIT_FAILURE的原因。

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

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