使用 pimpl 移动类无法编译

Move of class with pimpl won't compile

本文关键字:编译 pimpl 移动 使用      更新时间:2023-10-16

在下面的例子中,怎么可能正确调用~CImpl,但是当需要移动类时,编译器说它有一个不完整的类型?

如果将 Impl 的声明移动到它工作的标头,我的问题是为什么析构函数被称为 fine,所以看起来类型并不完整,但在移动时出现问题。

文件: C.hpp

#include <memory>
class Impl;

class C
{
public:
    C();
    ~C();
    C(C&&) = default;
    C& operator=(C&&) = default;
    std::unique_ptr<Impl> p;
};

文件 C.cpp

#include "C.hpp"
#include <iostream>
using namespace std;
class Impl
{
public:
    Impl() {}
    virtual ~Impl() = default;
    virtual void f() = 0;
};
class CImpl: public Impl
{
public:
    ~CImpl()
    {
        cout << "~CImpl()" << endl;
    }
    void f()
    {
        cout << "f()" << endl;
    }
};

C::C():
    p(new CImpl())
{}
C::~C()

文件:主.cpp

#include <iostream>
#include <vector>
#include "C.hpp"
using namespace std;
int main(int argc, char *argv[])
{
    vector<C> vc;
    // this won't compile
    //vc.emplace_back(C());
    C c;
    C c2 = move(c); // this won't compile
}

编译器输出:

+ clang++ -std=c++11 -Wall -c C.cpp
+ clang++ -std=c++11 -Wall -c main.cpp
In file included from main.cpp:3:
In file included from ./C.hpp:1:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/memory:80:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:65:16: error: invalid application of 'sizeof' to an incomplete type 'Impl'
        static_assert(sizeof(_Tp)>0,
                      ^~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:184:4: note: in instantiation of member function
      'std::default_delete<Impl>::operator()' requested here
          get_deleter()(__ptr);
          ^
./C.hpp:12:5: note: in instantiation of member function 'std::unique_ptr<Impl, std::default_delete<Impl> >::~unique_ptr' requested here
    C(C&&) = default;
    ^
./C.hpp:3:7: note: forward declaration of 'Impl'
class Impl;
      ^
1 error generated.

析构函数工作正常,因为析构函数的(空)主体位于 C 源文件中,可以访问 Impl 的完整定义。但是,移动构造函数和移动赋值在标头中是默认(定义的),没有定义Impl

您可以做的是在标头中C(C&&);,在源文件中C::C(C&&) = default;