相关疑难解决方法(0)

Pimpl - 为什么可以在不完整的类型上调用make_unique

为什么make_unique调用编译?make_unqiue不要求其模板参数是完整类型吗?

struct F;
int main()
{
  std::make_unique<F>();
}

struct F {};
Run Code Online (Sandbox Code Playgroud)

从orignated问题我的"问题"与我PIMPL实现:

我确实理解为什么析构函数必须在用户声明并在实现类(PIMPL)的cpp文件中定义.

但是移动包含pimpl的类的构造函数仍会编译.

class Object
{};

class CachedObjectFactory
{
public:
  CachedObjectFactory();

  ~CachedObjectFactory();
  std::shared_ptr<Object> create(int id) const;

private:
  struct CacheImpl;
  std::unique_ptr<CacheImpl> pImpl;
};
Run Code Online (Sandbox Code Playgroud)

现在cpp文件:

// constructor with make_unique on incompete type ?
CachedObjectFactory::CachedObjectFactory()
  : pImpl(std::make_unique<CacheImpl>())
{}

struct CachedObjectFactory::CacheImpl
{
  std::map<int, std::shared_ptr<Object>> idToObjects;
};

//deferred destructor
CachedObjectFactory::~CachedObjectFactory() = default;
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么这个编译?为什么建筑和破坏之间存在差异?如果析构函数的实例化和default_deleter的实例化是一个问题,为什么make_unique的实例化不是问题?

c++ templates pimpl-idiom unique-ptr language-lawyer

26
推荐指数
2
解决办法
1134
查看次数