Does pImpl fundamentally solve C++ DLL issue?

2019-07-12 12:21发布

I'm trying to export a C++ class out of a DLL with stl members.

Here's my main class.

class MATHFUNCSDLL_API MyMathFuncsImpl
    {
    public: 

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

Using the methods works, but gives warnings on VS 2012 about std::string and std::vector not having a dll-interface. Now when I do this -

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;
    };

I get no warnings, and it also works. My question is this: does having an interface like this really solve the problem (stl members might be implemented differently across dll boundary), or is it just a trick to suppress compiler issues?

标签: c++ dll stl
1条回答
Emotional °昔
2楼-- · 2019-07-12 12:55

Yes.

You should never use inline functions in a DLL interface. And that includes constructors and destructors which should be explicitly declared but defined in an implementation file. For C++ that means you should use the pImpl idiom or virtual base classes.

The reason to avoid inline functions is that they may change from one release to the next while the DLL stays the same. Any mismatch will cause weird and horrible problems.

查看更多
登录 后发表回答