It's a fairly contrived example, but I have a class that owns a std::vector<std::unique_ptr<Base>>, I wish to return a subset of this vector, as raw pointers, to represent the fact that ownership and/or lifetime management is to be handled by the library. In the example below, I have simulated this with the function getRawPointers.
What are 'safer' alternatives to this design pattern? Please observe that I do not wish to use shared_ptr semantics.
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
class base
{
public:
virtual ~base() = default;
virtual void print() = 0;
};
class derived : public base
{
public:
explicit derived(int id_)
: base()
, id(id_)
{}
void print() override
{
std::cout << id << " - Derived.\n";
}
derived(const derived& other) = delete;
derived(derived&& other) noexcept = default;
derived& operator=(const derived& other) = delete;
derived& operator=(derived&& other) noexcept = default;
int id;
};
std::vector<std::unique_ptr<base>> UniquePtrObjects;
std::vector<base*> getRawPointers(int offset, int count)
{
auto returnRange = std::vector<base*>();
std::for_each(UniquePtrObjects.begin() + offset, UniquePtrObjects.begin() + offset + count,
[&returnRange](std::unique_ptr<base>& i) {returnRange.push_back(i.get()); });
return returnRange;
}
int main()
{
UniquePtrObjects.push_back(std::make_unique<derived>(1));
UniquePtrObjects.push_back(std::make_unique<derived>(2));
UniquePtrObjects.push_back(std::make_unique<derived>(3));
UniquePtrObjects.push_back(std::make_unique<derived>(4));
UniquePtrObjects.push_back(std::make_unique<derived>(5));
UniquePtrObjects.push_back(std::make_unique<derived>(6));
auto result = getRawPointers(1, 3);
for (auto& element : result)
{
element->print();
}
std::cin.get();
}
Aucun commentaire:
Enregistrer un commentaire