背景
对于类的设计与定义,我们习惯上使用“指向实现的指针”, 或者叫PImpl。例如下面的类:
// widget.h(接口)
class widget {
// 公开成员
private:
struct impl; // 实现类的前置声明
impl* ptr;
};
// widget.cpp(实现)
struct widget::impl {
// 实现细节
};
1、对于impl类的改动,不会影响到widget类相应编绎单元的重新编绎,从编绎角度能够较大提供编绎效率。
2、有利于构建稳定的ABI接口。即是某个库使用了impl,则更新了impl的实现之后,新版本库能够兼容旧的ABI。
问题
正常代码
为了对比下面智能指针代码,这里给出一个正常使用raw pointer的示例代码
//widget.h
struct Impl;
class Widget{
public:
~Widget() = default;
private:
// std::unique_ptr<Impl> ptr_;
Impl* ptr_;
};
//widget.cpp
#include "widget.h"
#include <memory>
class Impl {
};
#include "widget.h"
int main(int argc, char** argv) {
Widget widget;
return 0;
}
TARGET=main
all:$(TARGET)
OBJ=widget.o main.o
main:$(OBJ)
g++ -std=c++11 -g -o $@ $(OBJ) -lpthread
%.o:%.cpp
g++ -std=c++11 -g -c $<
clean:
rm -f *.o
rm -f $(TARGET)
智能指针替换代码
在c++11中,有了smart pointer,我们正常来说会使用智能指针去替换raw pointer。例如把widget.cpp修改成如下代码:
//widget.h
struct Impl;
class Widget{
public:
~Widget() = default;
private:
std::unique_ptr<Impl> ptr_;
//Impl* ptr_;
};
执行make之后,我们发现报了一个错,大致如下:
In file included from /usr/include/c++/4.8/memory:81:0,
from test.h:4,
from test.cpp:1:
/usr/include/c++/4.8/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = Widget::Impl]’:
/usr/include/c++/4.8/bits/unique_ptr.h:184:16: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = Widget::Impl; _Dp = std::default_deleteWidget::Impl]’
test.h:6:7: required from here
/usr/include/c++/4.8/bits/unique_ptr.h:65:22: error: invalid application of ‘sizeof’ to incomplete type ‘Widget::Impl’
static_assert(sizeof(_Tp)>0,
^
make: *** [test.o] Error 1
刚开始的时候一头雾水,没理清楚。我们关注一下报错的地方。unique_ptr这里,它由于需要在析构的时候,去调用对应的Impl类的析构函数。而这里用的只是前置声明,static_assert(sizeof(_Tp)>0表示这里必须要知道Impl类的完整定义。那么问题就比较清楚了。widget类对象在作用域结束的时候,会自动生成析构函数,而析构函数中,我们必须要知道Impl类的完整定义,编绎器才能调用其析构函数。
解决方案
可以为Widget声明析构函数,并在定义的当前编绎单元,让其对Impl的定义可见即可。如下代码:
我们先在widget.h中声明析构函数,并在widget.cpp中定义析构函数,并在widget.cpp中能够看到类Impl的定义即可。代码如下:
//widget.h
struct Impl;
class Widget{
public:
~Widget();
private:
// std::unique_ptr<Impl> ptr_;
Impl* ptr_;
};
//widget.cpp
#include "widget.h"
#include <memory>
class Impl {
};
Widget::~Widget() = default;
总结
凡事遇到问题,必须要有刨根问底的精神,方能一步步往前。有些问题必须要知其所以然才能够通透。路漫漫其修远兮,吾将上下而求索。
本文探讨了在C++中使用unique_ptr实现PImpl模式时遇到的编译错误,原因是unique_ptr在析构时需要Impl类的完整定义。解决方案是在头文件中声明析构函数,并在包含Impl类定义的编译单元中定义析构函数。
289

被折叠的 条评论
为什么被折叠?



