Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

singleton pattern and std::unique_ptr

std::unique_ptr uniquely controls the object it points to and, hence, does not utilize reference counting. A singleton ensures only one object may be created utilizing reference counting.

Would then std::unique_ptr perform identically to a singleton?

like image 224
Mushy Avatar asked Apr 09 '13 15:04

Mushy


3 Answers

A singleton ensures only one instance of a type.

A unique_ptr ensures only one smart pointer to any instance.

like image 98
Drew Dormann Avatar answered Nov 18 '22 05:11

Drew Dormann


Would then std::unique_ptr perform identically to a singleton?

No. Let's say we have class Foo that's intended to be a singleton. Using a typical singleton pattern, there's no way to construct more than one Foo.

Having a std::unique_ptr<Foo> means there will be one pointer to a particular instance of Foo, but that doesn't prevent the creation of other instances of Foo (either with other unique_ptrs or with raw pointers to local variables). Thus Foo, wouldn't be a singleton.

like image 33
Adrian McCarthy Avatar answered Nov 18 '22 06:11

Adrian McCarthy


std::unique_ptr achieves single ownership semantics by only providing a move constructor and no copy constructor or assignment operator.

It is not a case of singleton at all, since you can have multiple unique_ptrs referencing different instances of the same type. A singleton doesn't let you construct the type directly, but provides an accessor that manages a sole instance.

Also, Drew's assertion that

"A unique_ptr ensures only one smart pointer to any instance."

is false. If you simply do:

T* nt = new T;
std::unique_ptr<T> up1(nt);
std::unique_ptr<T> up2(nt);

then you have two unique pointers owning the same resource - and you will only notice a problem at run time, not compile time. Of course, this is incorrect usage of unique_ptr, but this reinforces that a unique_ptr does not ensure you anything, it is simply a pointer container that holds sole ownership from its own perspective, and through its api, makes it hard to accidentally create temporary copies.

Furthermore, you can have other (smart) pointer types pointing to the same raw pointer/resource independently of any unique_ptr. It is completely up to the using code to define ownership and lifetime policies of its resources and smart pointer instances

like image 4
Preet Kukreti Avatar answered Nov 18 '22 06:11

Preet Kukreti