最近我碰到了C++的Singleton设计模式的实现/实现.看起来像这样(我从现实生活中采用了它):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
Run Code Online (Sandbox Code Playgroud)
从这个声明我可以推断出实例字段是在堆上启动的.这意味着存在内存分配.对我来说完全不清楚的是,什么时候内存将被解除分配?还是有漏洞和内存泄漏?好像在实施中存在问题.
我的主要问题是,如何以正确的方式实施它?
我想声明std::make_unique函数是我班级的朋友.原因是我想声明我的构造函数protected并提供一种使用创建对象的替代方法unique_ptr.这是一个示例代码:
#include <memory>
template <typename T>
class A
{
public:
// Somehow I want to declare make_unique as a friend
friend std::unique_ptr<A<T>> std::make_unique<A<T>>();
static std::unique_ptr<A> CreateA(T x)
{
//return std::unique_ptr<A>(new A(x)); // works
return std::make_unique<A>(x); // doesn't work
}
protected:
A(T x) { (void)x; }
};
int main()
{
std::unique_ptr<A<int>> a = A<int>::CreateA(5);
(void)a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在我收到此错误:
Start
In file included from prog.cc:1:
/usr/local/libcxx-head/include/c++/v1/memory:3152:32: error: calling a protected constructor of class 'A<int>'
return …Run Code Online (Sandbox Code Playgroud) 我的班级有以下结构:
class S {
public:
S() {}
};
class T {
private:
std::unique_ptr<S> a;
T(S);
public:
static std::unique_ptr<T> make_item() {
std::unique_ptr<S> s_instance = std::make_unique<S>();
return std::make_unique<T>(std::move(s_instance));
}
};
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在 make_item 中创建 unique_ptr 时,它将构造函数视为私有的。
有没有办法允许在类本身的静态成员函数中使用私有构造函数?因为一个成员是 S(一个相当重的对象)的 unique_ptr,所以我们不希望使用副本。