【问题标题】:Forward declaration for boost::intrusive_ptr class to reduce compile timeboost::intrusive_ptr 类的前向声明以减少编译时间
【发布时间】:2018-12-13 18:00:32
【问题描述】:

我有 A 类,它使用 boost::intrusive_ptr 保存一些数据:

#include "Data.h"

class A {
    boost::intrusive_ptr<Data> data;
}

Data 是基类RefCounted 的继承者,其函数intrusive_ptr_releaseintrusive_ptr_add_ref 是根据需要实现的。

我要减少编译时间,所以我尝试使用前向声明:

class Data;

class A {
    boost::intrusive_ptr<Data> data;
}

它不编译说

'intrusive_ptr_release':未找到标识符

我尝试添加所需函数的声明:

class Data;

void intrusive_ptr_add_ref(RefCounted *);
void intrusive_ptr_release(RefCounted *);

class A {
    boost::intrusive_ptr<Data> data;
}

现在它说

'void intrusive_ptr_release(RefCounted *)': 无法转换参数 1 从 'Data *' 到 'RefCounted *' 指向是不相关的;转换 需要 reinterpret_cast、C-style cast 或 function-style cast

我理解编译器错误的含义:它不知道RefCountedData 的超类,因为Data 是一个不完整的类型。但是,无论如何,这里有什么方法或技巧可以避免在处理 boost 侵入指针时包含标头 Data.h 以加快编译速度?

【问题讨论】:

    标签: c++ boost forward-declaration


    【解决方案1】:

    我知道解决您的问题的一种方法是确保在您的头文件中没有(隐式)为A 定义构造函数或析构函数。最小的示例如下所示:

    (头文件)

    #include <boost/intrusive_ptr.hpp>
    class Data;
    
    struct A {
        boost::intrusive_ptr<Data> data;
        A();
        ~A();
    };
    
    void foo() {
       A a;
    }
    

    然后,您将在某处有一个 .cpp 文件,该文件将为 A 定义(可能是默认的)构造函数和析构函数,并包含类 Data 的定义。

    【讨论】:

    • 很棒的答案。有趣(对我来说有点违反直觉)必须牺牲运行时性能(我的意思是使 ctor/dtor 不内联)以加快编译速度。
    • @Nick 总是如此。通过使东西不内联,您牺牲了编译时内联并获得了编译速度。不过,LTO 可能会来拯救。
    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多