• Impl模式实现之注意内联


    最近学习muduo源码时,对于内联函数有了更深刻的认知.

    内联(inline)在代码执行方面具有优势,但是有时使用不当,或者稍微不注意,就会造成编译错误.

    以下将通过Impl实现说明一二:

     头文件:

     1 #ifndef MUDUO_TEMP_H
     2 #define MUDUO_TEMP_H
     3 
     4 #include <memory>
     5 
     6 class Temp
     7 {
     8 public:
     9     Temp();
    10     ~Temp();
    11 
    12 private:
    13     class Impl;
    14     std::unique_ptr<Impl> impl_;
    15 };
    16 
    17 
    18 #endif //MUDUO_TEMP_H

    源文件:

     1 #include "Temp.h"
     2 
     3 class Temp::Impl
     4 {
     5 public:
     6     Impl() = default;
     7 
     8     ~Impl() = default;
     9 };
    10 
    11 Temp::Temp()
    12         : impl_(new Impl())
    13 {
    14 
    15 }
    16 
    17 Temp::~Temp()
    18 {
    19 
    20 }

     解释:

    (1)构造函数在源文件实现,比较容易理解,因为在头文件中并未具体实现Impl,无法通过new创建Impl实例;

    (2)尽管析构函数是空的,但是也必须放在源文件中进行定义,否则编译期隐式声明的~Temp() inline展开的时候无法寻找到Impl()::~Impl的声明,会出现编译报错.

    PS:

    如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!

  • 相关阅读:
    L3-015. 球队“食物链”【DFS + 剪枝】
    L3-002. 堆栈【主席树 or 线段树 or 分块】
    PTA L1-006 连续因子【暴力模拟】
    【路由和交换之H3C自导自演】
    【ospf-stub区域配置】
    【ospf-链路验证】
    【ospf-vlink虚拟连接】
    【c学习-14】
    【c学习-13】
    【php学习-5】
  • 原文地址:https://www.cnblogs.com/jason1990/p/9894485.html
Copyright © 2020-2023  润新知