我明白为什么在编译代码时出现 C4251 警告,如中所述here http://msdn.microsoft.com/en-us/library/esew7y1w.aspx。我的问题是,如果可访问的导出类成员来自 STL,我们可以忽略 C4251 警告吗?我举一个简单的例子来说明我的问题:
dll.h
#include <iostream>
#include <string>
using namespace std;
class __declspec(dllexport) HelloWorld
{
public:
string name;
HelloWorld();
HelloWorld(const string &str);
};
dll.cpp
#include "dll.h"
HelloWorld::HelloWorld()
{
name ="";
}
HelloWorld::HelloWorld(const string &str)
{
name = str;
}
我得到的警告信息如下:
Warning 1 warning C4251: 'HelloWorld::name' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'HelloWorld' *\dll.h 9
我的问题是:我可以忽略这个警告吗?我使用这个库的方式也很简单:
#include "dll.h"
#include <iostream>
using namespace std;
int main(void)
{
HelloWorld myworld;
myworld.name = "Tom's world";
cout<<myworld.name<<endl;
return 0;
}
您可以忽略,但您应该了解为什么会发生这种情况以及您可能遇到的问题是什么。
模板在编译时启动。这意味着它可能取决于您编译代码的方式。最有可能更改代码的是预编译器定义(例如 #define _NDEBUG 或 -D_NDEBUG 作为命令行参数)。
如果您的 DLL 接口包含依赖于编译时发生的事情的对象类型,则 DLL 的所有客户端必须确保这些类型在其代码中的编译方式与您的代码中的编译方式相同,否则可能会发生错误。
相同的编译也意味着使用相同的编译器。编译器之间的差异也会导致生成的可执行文件之间的代码不同,并且不同的编译器通常使用不同的 STL 库。
我举个例子:
template <typename T>
class A
{
int m_data;
#ifndef NDEBUG
int m_debugData;
#endif
public:
void func()
{
m_data =0;
#ifndef NDEBUG
m_debugData = 0;
#endif
}
};
在此示例中,如果您的 DLL 是使用 NDEBUG 编译的,并且使用代码是在没有 NDEBUG 的情况下编译的,则从用户代码中调用 func() 可能会导致运行时错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)