C++ STL and DLLs
C++ STL and DLLs
我知道这个问题已经以类似的方式被问了很多次,但我并不肯定我已经完全掌握了这里涉及的概念。我目前正在做一些小的学习项目(因为我停止使用C++一段时间并希望重新使用它),从我所读到的内容来看,在 DLL 中使用 STL 时存在一些问题。
但是,从我收集的信息来看,有两种方法可以避免可能出现的问题。
方法 1:DLL 的用户必须具有相同的编译器和相同的 C 运行时库。
方法 2:隐藏所有 STL 类成员,不直接访问。
但是,当涉及到方法 2 时,我知道客户端无法直接访问 STL 类成员以使此方法正常工作,但这是否意味着:
//Note all the code in this example was written directly in my web broswer with no checking.
#ifdef SAMPLEDLL_EXPORTS
#define SAMPLE_API __declspec(dllexport)
#else
#define SAMPLE_API __declspec(dllimport)
#endif
class SAMPLE_API SampleClass
{
std::map<int, std::string> myMap;
public:
SampleClass();
~SampleClass();
void addSomething(int in_Key, char* in_Val)
{
std::string s(in_Val);
myMap.insert( std::pair<int, std::string>(in_Key, s) );
};
bool getHasKey(int in_Key)
{
return myMap.find(in_Key) != myMap.end();
};
};
会工作吗?
正如Hans Passant在评论中指出的那样,您的示例有点可疑,因为您将所有方法定义都内联了。 但是,假设您将定义移动到一个单独的.cpp文件中,然后将其构建到 DLL 中。
它不会安全。
从一开始,我们就有了这个:
class SAMPLE_API SampleClass
{
std::map<int, std::string> myMap;
我不需要再看了,因为我们可以立即看到 SampleClass 的大小取决于 std::map 的大小,而标准没有指定。 因此,虽然你可以说 SampleClass 不会"公开"它的映射,但它实际上确实如此。 您可以使用 Pimpl 技术来克服这个问题,并真正从您类的 ABI 中隐藏地图。
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- BoostPython and CMake
- OpenSSL BIO and SSL_read
- Gurobi GRBModel and GRBmodel in C++
- std::visit and std::variant usage
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- Directx12 and keystrokes
- different between int **arr =new int [ n]; and int a[i][j]?
- C++ getenv and setenv
- Inference pytorch C++ with alexnet and cv::imread image
- Visual Studio 2019 C++ and std::filesystem
- 保证逻辑 AND 表达式中的函数调用
- python ctypes and C++ pointers
- C++ const char with .begin() and .end()
- Simulink and DLLs
- C++ STL and DLLs