lundi 14 décembre 2020

std::vector const reference and std::make_shared copy constructor [closed]

Consider the following code:

std::vector<std::shared_ptr<UniqueKeyGeneratorI>> keygens;
const auto hws = keyProvider.GetHWProfile().GetHWs();
for (const auto& hw : hws)
  keygens.push_back(std::make_shared<HW>(hw));

The function GetHWs() returns a const std::vector<HW>& (const reference), like shown:

class HWProfile
{
public:
  const std::vector<HW>& GetHWs() const { return mHWs; }
private:
  std::vector<HW> mHWs;
};

HW is a class inheriting from abstract base class UniqueKeyGeneratorI. I am trying to call the std::make_shared() copy constructor here. The code above works, but my question is this: At first, I wrote the exact same code, but with a very slight change

const auto& hws = keyProvider.GetHWProfile().GetHWs();

(the change is const auto& return type isntead of const auto). With this, the program did not work - it did not crash, but the copy constructor was not called - the objects were empty, just as if I called

keygens.push_back(std::make_shared<HW>());

instead of

keygens.push_back(std::make_shared<HW>(hw));

Why is this? Why do I need to copy the return value from the function returning const reference to call the copy constructor? What's wrong with using const auto& when dealing with a function returning const std::vector<>& and then range-based for loop iterating with another const auto&?

Aucun commentaire:

Enregistrer un commentaire