我的班级有以下结构:
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,所以我们不希望使用副本。
War*_*ers 16
正如 yksisarvinen 在评论中提出的那样,解决此问题的一种方法是make_unique<T>将std::unique_ptr<T>(new T(S)).
class S {
public:
S() {}
};
class T {
private:
std::unique_ptr<S> a;
T(S);
public:
static std::unique_ptr<T> make_item() {
// Create S
std::unique_ptr<S> s_instance = std::make_unique<S>();
return std::unique_ptr<T>(new T(s_instance));
}
};
Run Code Online (Sandbox Code Playgroud)