从函数返回后,shared_ptrs销毁了自己

时间:2019-07-18 12:21:44

标签: c++ shared-ptr make-shared

我有一个shared_ptr向量,但是从函数调用返回后,它被销毁了,但是只有在从填充函数返回后,它的元素才是第一个和第二个[0],[1]。

class SettingsFactory
{
public:
    explicit SettingsFactory(std::vector<std::shared_ptr< AppSettingEntity > >); //CTOR
    ~SettingsFactory();

    MDSettings& CreateMarketDataSettings();
    ExecutionSettings& CreateExecutionSettings();
    StrategySettings& CreateStrategySettings();
private:
    std::vector<std::shared_ptr< AppSettingEntity >>& m_vec;
    void Initialize();


};

MDSettings& SettingsFactory::CreateMarketDataSettings()
{
    bool result = false;
    MDSettings* md = new MDSettings;
    int i=0;
    for(auto &&e :m_vec)
    {
        i++;
        auto key = e.get()->GetSettingsKey();
        if(!key.compare("LOGGER_ENABLED"))
        {
             md->populate(e);
            result = true;
        }
       *** the distraction of the shared_ptr only happenn in the loop after the function call to populate****

    }
    if (!result)
    {
        std::string error("didnt load MarketDataSettings ");
        throw (error);
    }
    return *md;
}

void MDSettings::populate(std::shared_ptr<AppSettingEntity>& us)
{
    auto value = us.get()->GetSettingsValue();
    auto key = us.get()->GetSettingsKey();
    auto num = us.use_count();
    m_data[key] = value;//us.get()->GetSettingsValue();
   // m_data[us.get()->GetSettingsKey()] =us.get()->GetSettingsValue();
}

我不明白为什么,当我在填充函数中检查引用计数并且它是2且在调用之前是1且我还没有离开该函数时,

0 个答案:

没有答案