c – 通过减少填充标头的数量来隐藏实现细节

前端之家收集整理的这篇文章主要介绍了c – 通过减少填充标头的数量来隐藏实现细节前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个库.我有从外部调用的接口类.

我还有一个不应该从外面调用的内部引擎.

当我在这里和那里阅读时,我应该隐藏内部引擎类,甚至不填充它的标题.由于我有以下结构:

interface.hpp:

  1. #include "engine.hpp"
  2. class interface{
  3. private:
  4. enigne eng;
  5. };

interface.cpp:

  1. #include "engine.hpp"
  2. //code that uses member variables and functions from eninge

engine.hpp:

  1. class engine{};

解决填充“engine.hpp”的问题,我应该将代码更改为:

interface.hpp:

  1. class engine;
  2. class interface{
  3. private:
  4. some_smart_pointer<enigne> eng_ptr;
  5. };

interface.cpp:

  1. #include "engine.hpp"
  2. //code that uses member variables and functions from eninge

enigne.hpp:

  1. class engine{};

解决了这个问题.但是,从现在开始动态分配引擎.它的所有成员变量都在免费商店中.

我无法理解我必须改变我的设计并在免费商店上分配引擎来解决隐藏实现细节的问题.有更好的解决方案吗?

附:我不是在问这个解决方案为何有效.我知道如果我将它留在堆栈上,知道引擎类的大小是强制性的.我的问题是要求一个可以解决问题的不同设计.

编辑:

接口和引擎都有成员变量.

解决方法

你正在使用PIMPL习语.隐藏实现的另一种方法是使用接口,即抽象基类和工厂函数

interface.hpp:

  1. class interface{
  2. public:
  3. virtual ~interface(){}
  4. virtual void some_method() = 0;
  5. };
  6.  
  7. // the factory function
  8. static some_smart_pointer<interface> create();

interface.cpp:

  1. #include "interface.hpp"
  2. #include "engine.hpp"
  3.  
  4. class concrete : public interface{
  5. public:
  6. virtual void some_method() override { /* do something with engine */ }
  7. private:
  8. engine eng;
  9. };
  10.  
  11. some_smart_pointer<interface> create(){ return new concrete; }

main.cpp中

  1. #include "interface.hpp"
  2.  
  3. int main()
  4. {
  5. auto interface = create();
  6. interface->some_method();
  7.  
  8. return 0;
  9. }

这里的缺点是你必须动态分配接口而不是引擎.

有关PIMPL和接口herehere的更多讨论

编辑:

基于STL容器和Howard Hinnant的stack allocator,在免费商店中避免变量的第三种方法可以是:

interface.hpp:

  1. class interface{
  2. public:
  3. interface();
  4. ~interface();
  5.  
  6. // I disable copy here,but you can implement them
  7. interface(const interface&) = delete;
  8. interface& operator=(interface&) = delete;
  9.  
  10. private:
  11. engine* eng;
  12. };

interface.cpp:

  1. #include "interface.hpp"
  2. #include "engine.hpp"
  3. #include "short_alloc.h"
  4.  
  5. #include <map>
  6.  
  7. namespace
  8. {
  9. std::map<
  10. interface*,engine,std::default_order<interface*>,// use a stack allocator of 200 bytes
  11. short_alloc<std::pair<interface*,engine>,200>
  12. > engines;
  13. }
  14.  
  15. interface::interface():
  16. eng(&engines[this])
  17. // operator[] implicitly creates an instance and returns a reference to it
  18. // the pointer gets the address
  19. {
  20. }
  21.  
  22. interface::~interface()
  23. {
  24. // destroy the instance
  25. engines.erase(this);
  26. }

猜你在找的C&C++相关文章