【问题标题】:When forward declaring classes should I use attribute defines there too?向前声明类时,我也应该在那里使用属性定义吗?
【发布时间】:2017-06-16 14:16:57
【问题描述】:

当我向前声明类并且我有一个类似的定义时:

#define API __declspec(dllexport)

我应该用它还是不用它来声明函数?我知道当我完全声明类时我需要这样做(比如,使用 body 和东西),但我想知道是否也应该在前向声明中使用它。

【问题讨论】:

  • 定义API 之类的东西的全部意义在于,您可以根据上下文在__declspec(dllexport)__declspec(dllimport) 之间更改它。并且不可能将__declspec(dllimport) 放在定义 上,因为根据定义,导入符号的定义不应该对编译器可见。所以这应该总是在声明中进行。
  • 好的,谢谢,很有用。我确实有两个定义,但我只展示了一个来说明我的观点。
  • @CodyGray 类定义就是定义,将dllimport 放在那里确实有意义。

标签: c++ class forward-declaration


【解决方案1】:

一般来说,我的回答是“不”。

__declspec(dllexport)__declspec(dllimport) 属性只需要知道“我们需要导出这个”和“我们需要导入这个”的事实。 而在只有前向声明就足够的地方,这个事实并不重要,因为这意味着在这个地方只要知道这样的类存在就足够了。

最常见的用例之一是这样的:

// --- Library ---
// Library.h
class LIBRARY_API LibraryClass
{
     void SomeMethod();
}

// Library.cpp
#include "Library.h" // we include the declaration together with __declspec(dllimport)
void LibraryClass::SomeMethod() { /*do something*/ }


// --- Some module which uses Library ---
// Some class .h file
class LibraryClass; // forward declaration
class SomeClass
{
    std::unique_ptr<LibraryClass> mp_lib_class; 
    // forward decl of LibraryClass is enough 
    // - compiler does not need to know anything about this class

    // ...   
}

// Some class .cpp file
#include <Library/Library.h> 
// here we include LibraryClass declaration with __declspec(dllimport)

//...
SomeClass::SomeClass()
    : mp_lib_class(std::make_unique<LibraryClass>())
        // here we need to actually call LibraryClass code
        // - and we know that it's imported because of #include
{}

如果您在实际定义它的库中前向声明 LibraryClass - 放置 __declspec(dllexport) 不会改变任何内容,因为无论这些前向声明如何都导出类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2018-10-11
    • 2015-12-26
    相关资源
    最近更新 更多