Reputation: 76
I'm studying C++. To practice, I tried to implement a very simple singleton class, but I can't understand why this causes an error.
When I return a reference to it (which I think I should use it like that), like static unique_ptr<Singleton>& getInstance()
, it is accepted.
So, what's wrong here?
class Singleton
{
private:
static unique_ptr<Singleton> obj;
Singleton()
{
cout << "it's created!!\n";
}
public:
~Singleton()
{
cout << "it's desctructed!!\n";
}
static unique_ptr<Singleton> getInstance()
{
if (obj.get() == nullptr)
obj.reset(new Singleton());
return obj;
}
};
unique_ptr<Singleton> Singleton::obj{nullptr};
int main(){
unique_ptr<Singleton> ss = Singleton::getInstance();
return 0
}
/home/rt7/Desktop/ccProjects/cppTutorial/main.cc: In static member function ‘static std::unique_ptr<Singleton> Singleton::getInstance()’:
/home/rt7/Desktop/ccProjects/cppTutorial/main.cc:25:16: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Singleton; _Dp = std::default_delete<Singleton>]’
25 | return obj;
| ^~~
In file included from /usr/include/c++/11/bits/locale_conv.h:41,
from /usr/include/c++/11/locale:43,
from /usr/include/c++/11/iomanip:43,
from /usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h:72,
from /home/rt7/Desktop/ccProjects/cppTutorial/main.cc:1:
/usr/include/c++/11/bits/unique_ptr.h:468:7: note: declared here
468 | unique_ptr(const unique_ptr&) = delete;
Upvotes: 0
Views: 198
Reputation: 38549
The singleton is the object owner. Usually a raw pointer is returned if the ownership is not transfered.
static Singleton* getInstance()
{
if (!obj) // Simpler than obj.get() == nullptr
obj.reset(new Singleton());
return obj.get();
}
Upvotes: 2