2

I have three class members:

public:
    std::vector<std::shared_ptr<Object> > getObjects();
    std::vector<std::shared_ptr<const Object> > getObjects() const;

private:
    std::vector<std::shared_ptr<Object> > m_objects;

I'm getting a compiler error when I return m_objects in the const version of getObjects(), because m_objects does not match the return type (std::vector<std::shared_ptr<const Object>>).

In my workaround, I first reconstruct the object vector locally by iterating and then return the local vector, but is there a more optimized way of handling this scenario?

std::vector<std::shared_ptr<const Object> > objects;
for (auto & object: m_objects)
{
    objects.push_back(object);
}
return objects;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
grimgrom
  • 730
  • 1
  • 9
  • 18
  • 1
    I'm afraid not. Those are unrelated types. – Igor R. Jun 04 '19 at 17:18
  • Ok, but I suppose the content of the local variable wont be copied but moved in the case of assigning a variable to getObjects(), for example auto objects = objectManager->getObject();, where objectManager is a const pointer. – grimgrom Jun 04 '19 at 17:23
  • One solution is to not return a `vector` and instead make the class itself [into a container](https://stackoverflow.com/questions/7758580/writing-your-own-stl-container). Note that this may betray the class's intent and overcomplicate things. – user4581301 Jun 04 '19 at 17:42
  • 2
    How about simply `return {m_objects.begin(), m_objects.end()};`? –  Jun 04 '19 at 21:35

1 Answers1

1

You cannot cast from std::vector<std::shared_ptr<T>> to std::vector<std::shared_ptr<const T>>, even reinterpret_cast would yield undefined behavior. For details, the related question cast vector<T> to vector<const T> could help.

Creating a copy is the best that you can do. But, as Frank pointed out, it can be written more concise as return {m_objects.begin(), m_objects.end()}. That also avoids some unnecessary allocations, as the size of the final container is immediately known (in contrast to the push_back approach).

Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239