I'm not entirely sure if your question is about achieving this, but if you want behaviour from a shared_ptr
, where, if you release the value from one shared_ptr
, all the other shared pointers to the same value become a nullptr, then you can put a unique_ptr
in a shared_ptr
to achieve that behaviour.
void print(std::string name, std::shared_ptr<std::unique_ptr<int>>& ptr)
{
if(ptr == nullptr || *ptr == nullptr)
{
std::cout << name << " points to nullptr" << std::endl;
}
else
{
std::cout << name << " points to value " << *(*ptr) << std::endl;
}
}
int main()
{
std::shared_ptr<std::unique_ptr<int>> original;
original = std::make_shared<std::unique_ptr<int>>(std::make_unique<int>(50));
std::shared_ptr<std::unique_ptr<int>> shared_original = original;
std::shared_ptr<std::unique_ptr<int>> thief = nullptr;
print(std::string("original"), original);
print(std::string("shared_original"), shared_original);
print(std::string("thief"), thief);
thief = std::make_shared<std::unique_ptr<int>>(original->release());
print(std::string("original"), original);
print(std::string("shared_original"), shared_original);
print(std::string("thief"), thief);
return 0;
}
Output:
original points to value 50
shared_original points to value 50
thief points to nullptr
original points to nullptr
shared_original points to nullptr
thief points to value 50
This behaviour allows you to share a resource (like an array), then later reuse that resource while invalidating all the shared references to this resource.
auto_ptr
? If they're unique, it must mean they never get copied around (as multiple references would then exist, if only temporarily), and thenauto_ptr
should work just fine. Or, if you don't plan on using the smart pointer-supplied lifetime management anyway, use a raw pointer. – Axelshared_ptr
from factories, since there is a case for that being the best way pre-C++11. A throwingshared_ptr
->unique_ptr
conversion might be useful, it's a pain when you can't break rules even when you really want to! – Richma