I recently switched to C++11 and I'm trying to get used to good practices there. What I end up dealing with very often is something like:
class Owner
{
private:
vector<unique_ptr<HeavyResource>> _vectorOfHeavyResources;
public:
virtual const vector<const HeavyResource*>* GetVectorOfResources() const;
};
This requires me to do something like adding a _returnableVector and translating the source vectors to be able to return it later on:
_returnableVector = vector<HeavyResource*>;
for (int i=0; i< _vectorOfHeavyResources.size(); i++)
{
_returnableVector.push_back(_vectorOfHeavyResources[i].get());
}
Has anyone noticed similar problem? What are your thoughts and solutions? Am I getting the whole ownership idea right here?
UPDATE:
Heres another thing:
What if one class returns a result of some processing as vector<unique_ptr<HeavyResource>>
(it passes the ownership of the results to the caller), and it is supposed to be used for some subsequent processing:
vector<unique_ptr<HeavyResource>> partialResult = _processor1.Process();
// translation
auto result = _processor2.Process(translatedPartialResult); // the argument of process is vector<const HeavyResource*>
It can be assigned: class owner { std::unique_ptr<someObject> owned; public: owner() { owned=std::unique_ptr<someObject>(new someObject()); } };
(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.
An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope. A unique_ptr explicitly prevents copying of its contained pointer.
I would suggest that instead of maintaining and returning an un-unique_ptr
ed vector, you provide functions to access the elements directly. This encapsulates the storage of your resources; clients don't know that they are stored as unique_ptr
s, nor that they are kept in a vector
.
One possibility for this is to use boost::indirect_iterator
to dereference your unique_ptr
automatically:
using ResourceIterator =
boost::indirect_iterator<std::vector<std::unique_ptr<HeavyResource>>::iterator,
const HeavyResource>;
ResourceIterator begin() { return std::begin(_vectorOfHeavyResources); }
ResourceIterator end() { return std::end(_vectorOfHeavyResources); }
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With