C++: Warning C4251: Templates in exported classes
Say you have a template, be it from the STL or custom, as a field in a class which is __declspec(dllexport)'ed, you'll get this warning. The problem is that we're trying to export the template's declaration without its definition. This can make our program crash in runtime if we combine binaries which use different versions of the STL or our template. This could happen if we used dll's compiled with different versions of Visual Studio.
If you can't (or you're lazy) refactor your code in order not to export the class (you should only export interfaces), what you can do is export not the whole class but only the public methods which are used from other assemblies. Generically, if we have...
//This generates C4251
class __declspec(dllexport) A(){
public:
A();
virtual ~A();
void f();
private:
std::vector<int> m_vGeneratesC4251;
}
... and this dll's client assembly only needs to access f (because it instantiates A through a factory), we can solve the warning like this:
class A(){
public:
A();
__declspec(dllexport) virtual ~A();
__declspec(dllexport) void f();
private:
std::vector<int> m_vGeneratesC4251;
}
Comments
Post a Comment