1

I have a class in a DLL that looks something like this:

#ifdef LIB_EXPORT
#define LIB_API __declspec(dllexport)
#else
#define LIB_API __declspec(dllimport)
#endif

...

class LIB_API MyClass {
public:
  // ...public interface...
private:
 // ...some private fields...
 std::unique_ptr<OtherClass> otherPtr_;
};

Now, I think this could be a problem: if the client code uses a slightly different version of unique_ptr, the memory layout of a MyClass object effectively becomes different from what the code in the DLL might expect.

I don't really want to resort to the Pimpl idiom to hide unique_ptr from the public header. I could, potentially, roll my own simplified version of unique_ptr (I only need a subset of its functionality, for example I don't need custom deleters). But, before I try that, are there any other methods to resolve this?

1 Answer 1

5

The problem you've surmised is quite real, and it applies not only to layout of Standard library classes, but also your own classes. Unless your class meets the standard-layout rules, different compilers are not expected to use the same in-memory layout, even given exactly the same source code. The answer is that C++ classes shouldn't be exported at all.


Case #1: If you want unique_ptr for managing the lifetime of public objects of the DLL:

Export a factory function and deletion function from the DLL, and put a wrapper class inside the public header. The wrapper exists completely within the client, and therefore uses the client's version of unique_ptr only.

__declspec(dllexport) is NOT used on the wrapper class.


Case #2: If the DLL uses unique_ptr internally:

Instead of pimpl, you should use inheritance. The public header file contains a base class with protected constructor, pure virtual member functions and no data members at all. Again, __declspec(dllexport) is NOT used. A dllexport factory function is used to create new instances. Inside the DLL, you inherit from this interface type, the derived class adds all the data members and function bodies. None of the data members are ever seen by the client, so you can freely use C++ objects and the layout used is local to the DLL.


A side effect of both of these is that trivial member functions won't be inlined, which may negatively effect performance. But calling into the DLL for every member access is the only way to achieve decoupling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.