C++ STL and DLLs

C++ STL and DLLs

本文关键字:DLLs and STL C++      更新时间:2023-10-16

我知道这个问题已经以类似的方式被问了很多次,但我并不肯定我已经完全掌握了这里涉及的概念。我目前正在做一些小的学习项目(因为我停止使用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 中隐藏地图。