使用指针隐藏实现(Pimpl习惯用语) [英] Hide implementation by using a pointer (Pimpl idiom)

查看:121
本文介绍了使用指针隐藏实现(Pimpl习惯用语)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能实现以下目标:

Is it somehow possible, to accomplish the following:

x.hpp -其他许多类都包含此文件

x.hpp - this file is included by many other classes

class x_impl; //forward declare
class x {
    public:
        //methods...
    private:
        x_impl* impl_;
};

x.cpp -实现

#include <conrete_x>
typedef concrete_x x_impl;    //obviously this doesn't work
//implementation of methods...

所以基本上,我希望用户包括文件 x.hpp ,但不知道 conrete_x.hpp 标头.

So basically, I want the users to include the file x.hpp, but be unaware of the conrete_x.hpp header.

由于我只能通过指针使用concrete_x,并且它仅显示为私有数据成员,因此前向声明应足以使编译器知道为其准备多少空间.它看起来很像是著名的"pimpl惯用语".

Since I can use concrete_x only by a pointer and it appears only as a private data member, a forward declaration should be enough for the compiler to know how much space to prepare for it. It looks quite like the well-known "pimpl idiom".

您能帮我吗?

PS.我不想使用void*并将其抛弃..

PS. I don't want to use a void* and cast it around..

推荐答案

实际上,甚至可以完全向用户隐藏:

Actually, it's even possible to completely hide from the user:

// Foo.hpp
class Foo {
public:

    //...

private:
    struct Impl;
    Impl* _impl;
};

// Foo.cpp
struct Foo::Impl {
    // stuff
};

我想提醒您:

  • 您将需要编写适当的析构函数
  • 因此您还需要适当的复制构造函数,复制赋值运算符,移动构造函数和移动赋值运算符

有一些方法可以使PIMPL自动化,但要花费一些黑魔法(类似于std::shared_ptr所做的事情).

There are ways to automate PIMPL, at the cost of some black magic (similar to what std::shared_ptr does).

这篇关于使用指针隐藏实现(Pimpl习惯用语)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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