Pimpl with unique_ptr:为什么我必须将接口的构造函数的定义移至".cpp"? [英] Pimpl with unique_ptr : Why do I have to move definition of constructor of interface to ".cpp"?

查看:112
本文介绍了Pimpl with unique_ptr:为什么我必须将接口的构造函数的定义移至".cpp"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要我不将(c0>的)构造函数的定义移至标头B.h,该代码就可以工作.

The code would work file as long as I don't move the definition of constructor (of B) to the header B.h.

B.h

class Imp;  //<--- error here
class B{
    public:
    std::unique_ptr<Imp> imp;
    B();     //<--- move definition to here will compile error
    ~B();
    //// .... other functions ....
};

B.cpp

#include "B.h"
#include "Imp.h"
B::B(){ }
~B::B(){ }

Imp.h

class Imp{};

Main.cpp (编译我)

#include "B.h"

错误:删除了指向不完整类型的指针
错误:使用未定义的'Imp'C2027类型

Error: deletion of pointer to incomplete type
Error: use of undefined type 'Imp' C2027

我可以以某种方式理解必须将析构函数移至.cpp,因为Imp的析构可以称为:-

I can somehow understand that the destructor must be moved to .cpp, because destructure of Imp might be called :-

delete pointer-of-Imp;  //something like this

但是,我不理解为什么规则也涵盖构造函数(问题).

However, I don't understand why the rule also covers constructor (question).

我已阅读:-

  • Deletion of pointer to incomplete type and smart pointers
    describes reason why destructor need to be in .cpp.
  • std::unique_ptr with an incomplete type won't compile
    warns about the default destructor.

推荐答案

在异常退出的情况下,构造函数需要销毁该类成员.

The constructor needs to destroy the class members, in the case that it exits by exception.

我认为使构造函数noexcept不会有帮助,尽管也许应该有帮助.

I don't think that making the constructor noexcept would help, though maybe it should.

这篇关于Pimpl with unique_ptr:为什么我必须将接口的构造函数的定义移至".cpp"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆