首页 [设计模式]PIMPL惯用法分离内部实现和外部方法接口
文章
取消

[设计模式]PIMPL惯用法分离内部实现和外部方法接口

主要思想是使用pointer to implementation惯用法将类内部数据或者方法使用一个implementation隐藏起来。在 Efficient Mordern C++一书中 Item 22: When using the Pimpl Idiom, define special member functions in the implementation file.有详细讲解。

优点:数据隐藏,编译优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//////////////////////////////////////////////////////
// Parser.h
//////////////////////////////////////////////////////
class Parser {
public:
    Parser(const char *params);
    ~Parser();
    void parse(const char *input);

private:
    class Impl;     // Forward declaration of the implementation class
    Impl *impl_;    // PIMPL
};

//////////////////////////////////////////////////////
// Parser.cpp
//////////////////////////////////////////////////////
// The actual implementation definition:
class Parser::Impl {
public:
    Impl(const char *params) {
        // Actual initialization
    }
    void parse(const char *input) {
        // Actual work
    }
};

// Create an implementation object in ctor
Parser::Parser(const char *params)
: impl_(new Impl(params))
{}

// Delete the implementation in dtor
Parser::~Parser() { delete impl_; }

// Forward an operation to the implementation
void Parser::parse(const char *input) {
    impl_->parse(input);
}


本文由作者按照 CC BY 4.0 进行授权