0

I have a vector of shared_ptr but after return from a function call it is Destroyed, but only after returning from the populate function and the elements are the first and the second one [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();
}

I don't understand why, when I'm in the populate function im checking the reference count and it's 2 and before the call it's 1 and I didn't leave the function scoop yet

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
yaodav
  • 1,126
  • 12
  • 34
  • 3
    The fact that you take `std::vector>` by value in constructor, but you have a reference to that type as member makes me very suspicious. But we need [mcve] to help with your problem. – Yksisarvinen Jul 18 '19 at 12:26
  • Returning a reference to an object created with `new` in `CreateMarketDataSettings` is *very* confusing. You should either not use `new` (just return by value) or use a `unique_ptr` and return that. – Kevin Jul 18 '19 at 12:28
  • @Yksisarvinen thank you, I didn't see that. it's solved the problem – yaodav Jul 18 '19 at 12:31
  • Unrelated note: `us.get()->GetSettingsValue()` can be written much clearer as `us->GetSettingsValue()`. Smart pointers have operator `->` overloaded for that. – Yksisarvinen Jul 18 '19 at 12:31
  • Could you please provide the code where your `m_vec` got initialized (i.e the implementation of your `SettingsFactory` constructor)? That would be essential to your problem. – ph3rin Jul 18 '19 at 12:31
  • SettingsFactory::SettingsFactory(std::vector> & source):m_vec(source) { } – yaodav Jul 18 '19 at 12:32
  • @yaodav `SettingsFactory(std::vector >);` is not `SettingsFactory::SettingsFactory(std::vector> & source)` – UKMonkey Jul 18 '19 at 13:40

0 Answers0