【问题标题】:Access private constructor from public static member function using shared_ptr in C++ [duplicate]在 C++ 中使用 shared_ptr 从公共静态成员函数访问私有构造函数 [重复]
【发布时间】:2019-06-24 19:58:55
【问题描述】:

考虑下面的代码,我想将 A 对象的创建委托给一个名为 make 的方法,以允许该类的用户只创建包装在 std::shared_ptr 中的实例:

#include <memory>

class A {
private:    
    A() {}

public:
    static std::shared_ptr<A> make() {
        return std::make_shared<A>();
    }
};

int main() {
    std::shared_ptr<A> a = A::make();
    return 0;
}

我本来以为,因为make 是一个成员函数,它会被允许访问私有构造函数,但显然情况并非如此。编译程序失败,std::shared_ptr 的源代码中出现以下消息:

/usr/include/c++/8/ext/new_allocator.h:136:4: error: ‘A::A()’ is private within this context

我该如何解决这个问题?

【问题讨论】:

  • 您可以考虑使用pass key idiom。
  • 这与静态函数无关。就是std::make_shared 试图构造一个A,因为构造函数是私有的,所以它不能。

标签: c++ class shared-ptr


【解决方案1】:
class A {
private:
    A() {}

public:
    static std::shared_ptr<A> make() {
        return std::shared_ptr<A>(new A());
    }
};

【讨论】:

  • 如果你这样做,你会失去benefits of make_shared。
  • 缺点是分配了两个内存,一个用于 shared_ptr 控制块,一个用于 A 类实例对象。与std::make_shared 相比,它只会对控制块和对象进行一次分配。可能重要也可能不重要,具体取决于项目和使用模式。
猜你喜欢
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多