【问题标题】:Does pImpl fundamentally solve C++ DLL issue?pImpl 是否从根本上解决了 C++ DLL 问题?
【发布时间】:2015-07-31 21:09:38
【问题描述】:

我正在尝试从具有 stl 成员的 DLL 中导出 C++ 类。

这是我的主要课程。

class MATHFUNCSDLL_API MyMathFuncsImpl
    {
    public: 

       std::vector<int> vi;
      std::string getString();
      void setString(std::string s);
    private:
       std::string s;
    };

使用这些方法有效,但在 VS 2012 上会发出关于 std::string 和 std::vector 没有 dll 接口的警告。现在当我这样做时 -

class  MATHFUNCSDLL_API MyMathFuncs
    {
    public:
       MyMathFuncs()
       {
          pImpl = new MyMathFuncsImpl();
       }
       std::string getString()
       {
          return pImpl->getString();
       }

       std::vector<int> getVector()
       {
          return pImpl->vi;
       }

       void setString(std::string news)
       {
          pImpl->setString(news);
       }
    private:
       MyMathFuncsImpl* pImpl;
    };

我没有收到任何警告,它也有效。我的问题是:有这样的接口真的能解决问题吗(stl 成员可能在 dll 边界上以不同的方式实现),还是只是抑制编译器问题的一个技巧?

【问题讨论】:

  • 我认为这可行(根据 Zan Lynx 的回答),但对于使用不同标准 C++ 库实现的客户来说可能仍然存在问题

标签: c++ dll stl


【解决方案1】:

是的。

您不应该在 DLL 接口中使用内联函数。这包括应该显式声明但在实现文件中定义的构造函数和析构函数。对于 C++,这意味着您应该使用 pImpl 习惯用法或虚拟基类。

避免内联函数的原因是它们可能会从一个版本更改为下一个版本,而 DLL 保持不变。任何不匹配都会导致奇怪而可怕的问题。

【讨论】:

  • 如果 MyMathFuncs 返回一个指向 MyMathFuncsImpl 的指针,并且 MyMathFuncsImpl 有一个公共成员是 std::string,那会有问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2022-10-17
  • 2021-11-21
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
相关资源
最近更新 更多