Creating a class in a DLL using std::string. C4251 warning - c++

I would like to implement a simple class in a DLL, something like:
class MY_EXPORT_IMPORT MyClass
{
public:
//std::string anyPublicStr; //see point 3
protected:
std::string anyStr;
};
The problem is that Visual C++ compiler (2013 in this case) throws the following warning:
C:...MyClass.hpp:X: warning: C4251: 'MyClass::postfix' : class
'std::basic_string,std::allocator>'
needs to have dll-interface to be used by clients of struct 'MyClass'
I read several forums about why this warning is shown and how to solve it. But it is still not clear to me:
Most forums speak about exporting the templates, which make sense for templates, but std::string is already a specific type.
An other page said "Exporting std::string from a DLL is a VERY bad idea, for several reasons." Which make sense.
Others indicate as solution to encapsulate the parameter in a non-inline function. Well, in our case, the std::string is already protected, and switching to private does not solve the warning.
Personally I do not understand why this class could not just statically link the required STL libraries and make it to work without exporting anything. Or if the STL is dynamically linked, it should be also automatically linked in the dll.
Why is this Warning? How to solve it?

std::string is just a typedef:
typedef basic_string<char, char_traits<char>, allocator<char> >
string;
Regarding using STL on the dll interface boundary, generally it is simpler if you avoid that and I personally prefer it if possible. But the compiler is just giving you a warning and it doesn't mean that you will end in a problem. Have a look at: DLLs and STLs and static data (oh my!)

Related

Why is Microsoft using struct rather than class in new code?

So normally I wouldn't ask a question like this because it seems like it could be opinion based or start some sort of verbal war on coding practices, but I think there might be a technical reason here that I don't understand.
I was looking over the code in the header files for vcpkg (a library packing manager that Microsoft is creating and is "new" code) because reading code generally is a good way to learn things you didn't know.
The first thing I noticed was the use of using rather than typedef.
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h'
template<class P>
using ParseExpected = ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;
I haven't personally used using this way before and an answer from: What is the difference between 'typedef' and 'using' in C++11?. Essentially, using is the new way to do it, and the benefit is that it can use templates. So Microsoft had a good reason to use using instead of typedef.
Looking at 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/commands.h' I noticed that they did not use any classes. Instead it was only namespaces with a function or so in them. ie:
namespace vcpkg::Commands
{
namespace BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet);
}
}
I'm guessing that part of this is that the calling syntax looks essentially just like a static member function in a class, so the code performs the same but maybe saves some overhead by being a namespace instead of a class. (If anyone has any ideas on this too that would be great.)
Now the main point of all this. Why is Microsoft using structs instead of classes in their namespaces?
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h':
namespace vcpkg::Parse
{
/* ... Code I'm excluding for brevity ... */
struct ParagraphParser
{
ParagraphParser(RawParagraph&& fields) : fields(std::move(fields)) {}
void required_field(const std::string& fieldname, std::string& out);
std::string optional_field(const std::string& fieldname) const;
std::unique_ptr<ParseControlErrorInfo> error_info(const std::string& name) const;
private:
RawParagraph&& fields;
std::vector<std::string> missing_fields;
};
}
Searching stackoverflow, I found an old question: Why Microsoft uses a struct for directX library instead of a class?
Which the answers were essentially, you don't have to declare things as public as default and a comment way at the bottom saying that it was old code.
If vcpkg was old code I would be completely satisfied, however, this is new code. Is it just some style they have that is a carry over (but using vs typedef isn't)? Or is it to save a line of code (public:)? Or is there some sort of overhead benefit? Or some other thing I haven't considered at all?
The only differences between struct and class are:
the default member access (public vs private) and
the default inheritance if you inherit from the type (public inheritance vs private inheritance).
The end result of 1 will be the same once the author has finished adding public:/private: to the type. 2 you can easily control yourself by being explicit when you inherit, rather than rely on the default. It's hardly a big deal and doesn't really matter.
As to why Microsoft uses struct rather than class in their code, you will have to ask some Microsoft people.
Regarding the free functions vs static functions, I don't think there is any overhead in this with classes (I haven't measured this at all, I would just think that most compiler would recognize that the class is basically just a namespace for the function). The thing is just: You don't need a class.
Using a class with only static functions is basically abusing the class as a namespace. So if you are only doing that, then be explicit about it and just use a namespace. Having a class there would only be confusing since you would think that maybe there could be some state here and just see that there is non when you see that the function in the class is static.
This is especially relevant if this is used a bit wrongly. Imagine someone instantiates a class A a with static member function f to call a.f(). It is no problem regarding performance, since the construction is a no-op and it will pretty much be equivalent to A::f(). But for the reader it seems like there is some kind of state involved and that is just confusing.
Regarding the other two: using is just superior to typedef throught being able to use templates and is (IMO) better readable. The struct vs class issue is just something over what has the better defaults, its not a big difference, but most often, what you want is what a struct does, so there is no reason to use a class.
To be (more) compatible with C
To avoid making everything public by using the public: keyword, since that all COM objects for example have only public member functions.

Export dll method which returns STL object [duplicate]

I'm trying to export classes from a DLL that contain objects such as std::vectors and std::strings - the whole class is declared as DLL export through:
class DLL_EXPORT FontManager {
The problem is that for members of the complex types I get this warning:
warning C4251: 'FontManager::m__fonts' : class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used by clients of class 'FontManager'
with
[
_Kty=std::string,
_Ty=tFontInfoRef
]
I'm able to remove some of the warnings by putting the following forward class declaration before them even though I'm not changing the type of the member variables themselves:
template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>;
template class DLL_EXPORT std::vector<tCharGlyphProviderRef,std::allocator<tCharGlyphProviderRef> >;
std::vector<tCharGlyphProviderRef> m_glyphProviders;
Looks like the forward declaration "injects" the DLL_EXPORT for when the member is compiled but is it safe?
Does it really change anything when the client compiles this header and uses the std:: container on his side?
Will it make all future uses of such a container DLL_EXPORT (and possibly not inline)?
And does it really solve the problem that the warning tries to warn about?
Is this warning anything I should be worried about or would it be best to disable it in the scope of these constructs?
The clients and the DLL will always be built using the same set of libraries and compilers and those are header only classes...
I'm using Visual Studio 2003 with the standard STD library.
Update
I'd like to target you more though as I see the answers are general and here we're talking about std containers and types (such as std::string) - maybe the question really is:
Can we disable the warning for standard containers and types available to both the client and the DLL through the same library headers and treat them just as we'd treat an int or any other built-in type? (It does seem to work correctly on my side)
If so would should be the conditions under which we can do this?
Or should maybe using such containers be prohibited or at least ultra care taken to make sure no assignment operators, copy constructors etc will get inlined into the DLL client?
In general I'd like to know if you feel designing a DLL interface having such objects (and for example using them to return stuff to the client as return value types) is a good idea or not and why, I'd like to have a "high level" interface to this functionality...
Maybe the best solution is what Neil Butterworth suggested - creating a static library?
When you touch a member in your class from the client, you need to provide a DLL-interface.
A DLL-interface means, that the compiler creates the function in the DLL itself and makes it importable.
Because the compiler doesn't know which methods are used by the clients of a DLL_EXPORTED class it must enforce that all methods are dll-exported.
It must enforce that all members which can be accessed by clients must dll-export their functions too. This happens when the compiler is warning you of methods not exported and the linker of the client sending errors.
Not every member must be marked with with dll-export, e.g. private members not touchable by clients. Here you can ignore/disable the warnings (beware of compiler generated dtor/ctors).
Otherwise the members must export their methods.
Forward declaring them with DLL_EXPORT does not export the methods of these classes. You have to mark the according classes in their compilation-unit as DLL_EXPORT.
What it boils down to ... (for not dll-exportable members)
If you have members which aren't/can't be used by clients, switch off the warning.
If you have members which must be used by clients, create a dll-export wrapper or create indirection methods.
To cut down the count of externally visible members, use approaches such as the PIMPL idiom.
template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>;
This does create an instantiation of the template specialization in the current compilation unit. So this creates the methods of std::allocator in the dll and exports the corresponding methods. This does not work for concrete classes as this is only an instantiation of template classes.
That warning is telling you that users of your DLL will not have access to your container member variables across the DLL boundary. Explicitly exporting them makes them available, but is it a good idea?
In general, I'd avoid exporting std containers from your DLL. If you can absolutely guarantee your DLL will be used with the same runtime and compiler version you'd be safe. You must ensure memory allocated in your DLL is deallocated using the same memory manager. To do otherwise will, at best, assert at runtime.
So, don't expose containers directly across DLL boundaries. If you need to expose container elements, do so via accessor methods. In the case you provided, separate the interface from the implementation and expose the inteface at the DLL level. Your use of std containers is an implementation detail that the client of your DLL shouldn't need to access.
Alternatively, do what Neil suggest and create a static library instead of a DLL. You lose the ability to load the library at runtime, and consumers of your library must relink anytime you change your library. If these are compromises you can live with, a static library would at least get you past this problem. I'll still argue you're exposing implementation details unnecessarily but it might make sense for your particular library.
There are other issues.
Some STL containers are "safe" to export (such as vector), and some aren't (e.g. map).
Map for instance is unsafe because it (in the MS STL distribution anyway) contains a static member called _Nil, the value of which is compared in iteration to test for the end. Every module compiled with STL has a different value for _Nil, and so a map created in one module will not be iterable from another module (it never detects the end and blows up).
This would apply even if you statically link to a lib, since you can never guarantee what the value of _Nil will be (it's uninitialised).
I believe STLPort doesn't do this.
One alternative that few people seem to consider is not to use a DLL at all but to link statically against a static .LIB library. If you do that, all the issues of exporting/importing go away (though you will still have name-mangling issues if you use different compilers). You do of course lose the features of the DLL architecture, such as run-time loading of functions, but this can be a small price to pay in many cases.
The best way I found to handle this scenario is:
create your library, naming it with the compiler and stl versions included in the library name, exactly like boost libraries do.
examples:
- FontManager-msvc10-mt.dll for dll version, specific for MSVC10 compiler, with the default stl.
- FontManager-msvc10_stlport-mt.dll for dll version, specific for MSVC10 compiler, with the stl port.
- FontManager-msvc9-mt.dll for dll version, specific for MSVC 2008 compiler, with the default stl
- libFontManager-msvc10-mt.lib for static lib version, specific for MSVC10 compiler, with the default stl.
following this pattern, you will avoid problems related with different stl implementations. remember, the stl implementation in vc2008 differs from the stl implementation in the vc2010.
See your example using boost::config library:
#include <boost/config.hpp>
#ifdef BOOST_MSVC
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
class DLL_EXPORT FontManager
{
public:
std::map<int, std::string> int2string_map;
}
#ifdef BOOST_MSVC
# pragma warning( pop )
#endif
Found this article. In short Aaron has the 'real' answer above; Don't expose standard containers across library boundaries.
Though this thread is pretty old, I found a problem recently, which made me think again about having templates in my exported classes:
I wrote a class which had a private member of type std::map. Everything worked quite well untill it got compiled in release mode, Even when used in a build system, which ensures that all compiler settings are the same for all targets. The map was completely hidden and nothing was directly exposed to the clients.
As a result the code was just crashing in release mode. I gues, because different binary std::map instances were created for implementation and client code.
I guess the C++ Standard is not saying anaything about how this shall be handled for exported classes as this is pretty much compiler specific. So I guess the biggest portability rule is to just expose Interfaces and use the PIMPL idiom as much as possible.
Thanks for any enlightenment
In such cases, consider the uses of the pimpl idiom. Hide all the complex types behind a single void*. Compiler typically fails to notice that your members are private and all methods included in the DLL.
none of the workarounds above are acceptable with MSVC because of the static data members inside template classes like stl containers
each module (dll/exe) gets its own copy of each static definition...wow! this will lead to terrible things if you somehow 'export' such data (as 'pointed' above)...so don't try this at home
see http://support.microsoft.com/kb/172396/en-us
Exporting classes containing std:: objects (vector, map, etc) from a dll
Also see Microsoft's KB 168958 article How to export an instantiation of a Standard Template Library (STL) class and a class that contains a data member that is an STL object. From the article:
To Export an STL Class
In both the DLL and the .exe file, link with the same DLL version of the C run time. Either link both with Msvcrt.lib (release build) or
link both with Msvcrtd.lib (debug build).
In the DLL, provide the __declspec specifier in the template instantiation declaration to export the STL class instantiation from
the DLL.
In the .exe file, provide the extern and __declspec specifiers in the template instantiation declaration to import the class from the
DLL. This results in a warning C4231 "nonstandard extension used :
'extern' before template explicit instantiation." You can ignore this
warning.
And:
To Export a Class Containing a Data Member that Is an STL Object
In both the DLL and the .exe file, link with the same DLL version of the C run time. Either link both with Msvcrt.lib (release build) or
link both with Msvcrtd.lib (debug build).
In the DLL, provide the __declspec specifier in the template instantiation declaration to export the STL class instantiation from
the DLL. NOTE: You cannot skip step 2. You must export the
instantiation of the STL class that you use to create the data member.
In the DLL, provide the __declspec specifier in the declaration of the class to export the class from the DLL.
In the .exe file, provide the __declspec specifier in the declaration of the class to import the class from the DLL. If the
class you are exporting has one or more base classes, then you must
export the base classes as well. If the class you are exporting
contains data members that are of class type, then you must export the
classes of the data members as well.
If you use a DLL make initialization of all objects at event "DLL PROCESS ATTACH" and export a pointer to its classes/objects.
You may provide specific functions to create and destroy objects and functions to obtain the pointer of the objects created, so you can encapsulate these calls in a wrapper class of access at include file.
The best approach to use in such scenarios is to use the PIMPL design pattern.

Why can a user change from private to public?

I've made a programm with libraries.
One library has a interface for to include a header for an extern programm call:
class IDA{
private:
class IDA_A;
IDA_A *p_IDA_A;
public:
IDA();
~IDA();
void A_Function(const char *A_String);
};
Then I opened the header with Kate and placed
class IDA_A;
IDA_A *p_IDA_A;
into the public part.
And this worked?! But why? And can I avoid that?
Greeting
Earlybite
And this worked?!
Yes
But why?
private, protected and public are just hints to the C+++ compiler how the data structure is supposed to be used. The C++ compiler will error out if piece of C++ source doesn't follow this, but that's it.
It has no effect whatsoever on the memory layout. In particular the C++ standard mandates, that member variables of a class must be laid out in memory in the order they are declared in the class definition.
And can I avoid that?
No. In the same way you can not avoid, that some other piece of code static_casts a (opaque) pointer to your class to char* and dumps it out to a file as is, completely with vtable and everything.
If you really want to avoid the user of a library to "look inside" you must give them some handle value and internally use a map (std::map or similar) to look up the actual instance from the handle value. I do this in some of the libraries I develop, for robustness reasons, but also because some of the programming environments there are bindings for don't deal properly with pointers.
Of course this works. The whole private-public stuff is only checked by the compiler. There are no runtime-checks for this. If the library is already compiled, the user only needs the library file (shared object) and the header files for development. If you afterwards change the header file in the pattern you mentioned, IDA_A is considered public by the compiler.
How can you avoid that? There is no way for this. If another user changes your headerfile, you can do nothing about it. Also is the question: Why bother with it? It can have very ugly side-effects if the headerfile for an already compiled lib is been changed. So the one who changes it also has to deal with the issues. There is just some stuff you dont do. One of them is moving stuff in headers around for libraries (unless you are currently developing on that library).
You've got access to the p_IDA_A member variable, and this is always possible in the manner you've outlined. But it is of type IDA_A, which for which you only have a declaration, but not the definition. So you can not do anything meaningful with it. (This method of data hiding is called the pimpl idiom).

Passing unmanaged template class instance as parameter in different dll fails compilation

I have unmanaged, template class for thread safe queue:
template<class T>
public class TSQueue {...}
And Producer class:
public ref class Producer
{
Producer(TSQueue<int>* Q) {...}
};
Producer is used in following way:
Producer^ p = gcnew Producer(new TSQueue<int>());
Both are defined in one C++/CLI DLL Producer.DLL.
When Producer is instantiated and provided with TSQueue< int >* inside this DLL, there are no problems with compilation and execution.
But, when I try to instantiate Producer with TSQueue< int >* in another, C++/CLI dll I am having the following compiler error:
Error 23 error C2664: 'Producer(TSQueue<int>*)' : cannot convert parameter 1 from 'TSQueue<T> *' to 'TSQueue<int> *'
As if compiler cannot determine the type of Q I provide to Producer constructor.
I have added reference to Producer.DLL.
Does anyone know how to overcome this problem.
IMO, adding reference to the DLL isn't enough since we are dealing here w/ "native" templates and not w/ generics.
Please make sure that your other DLL has a #include directive to the header of TSQueue
You need to include the complete definition of TSQueue in both libraries. Don't make it part of the interface use it only internally. If it needs to be a part of the API, follow the advice from Hans Passant: make it a generic, or better, use the proper framework implementation.
As Hans Passant sad:
Fairly sure you have a type identity problem here, induced by having a native C++ template cross a module boundary. That's in general a notorious problem in C++, templates don't have external linkage. It is easy to solve in C++/CLI by using generics, you should have a drop-in replacement for TSQueue from the .NET Queue<> class, ConcurrentQueue<> if it needs to be thread-safe.
But the generics cannot be used for unmanaged types, so I am using type specific unmanaged container class.

Mixing MFC and STL [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Would you mix MFC with STL? Why?
Sure. Why not?
I use MFC as the presentation layer, even though the structures and classes in the back-end use STL.
Use STL whenever you can, use MFC when no alternative
I mix them all the time. The only minor PITA was serialization - the MFC containers (CArray, CList, CStringArray, etc.) support CArchive serialization, but when using STL containers you have to roll your own code. In the end I switched to using boost::serialization and dumped the MFC CArchive stuff.
Yes, I have mixed them before without problems. However, after using MFC for over a decade, I would never consider using it for a new project.
I use MFC for all my C++ projects, since none of my projects are console. MFC is elegant solution for Windows C++ developers. I hate QT, and I wont use WX on Windows. I dont care about portability, since my applications are only for Windows. I love MFC/ATL's CString class, std::string is very raw, doesn't have any "String" features in it. std::string is nothing more than vector<char>.
For all data storage and algorithms, I use STL. I do also use ConcRT PPL template classes, which are very much same as STL.
For collections in the data layer. I have no data to support this, but my suspicion is that the templated STL collections are more performant than their MFC counterparts.
Yes I do mix 'em because I find MFC too unwieldy for normal natural looking c++. Though you might have to write some code for conversions where your STL code talks to MFC code.
It was a very bad idea before Visual Studio 2003's (nearly) full support for the C++ Standard. Now it's not a bad idea at all. Whether it's a good idea depends on the context and what the skillset of your team is.
Yes, if both of the following conditions hold:
1) The language chosen for the project is C++ (which, of course, includes the STL - the S in the STL is for "Standard").
2) After a careful analysis, no better alternative is found or considered appropriate for the GUI support than MFC, and my development team goes for it.
It depends on what your definition of "mixing" is.
If you simply mean creating a project that uses both STL and MFC I don't see any harm in that at all. They serve a different purpose.
when mixing STL with other microsoft headers, be sure to define NOMINMAX,
otherwise your std::min function will be garbled into a syntax error because of the min(a,b) macro.
You should not use standard exceptions in an MFC application - your app might hang if you throw it inside a dialog. See this question for the reasons: Why does my MFC app hang when I throw an exception?
I had a struct with many simple type fields (UINT, CString, COLORREF, etc.). Project was compiling well.
Then I added a which I added a CArray to the struct. It wasn't compiling.
Then I implemented operator= and copy constructor for that struct (one using the other). It then compiled.
Some time after, doing maintenance to the struct I did an experiment: change the CArray to be a std::vector and remove the operator= and copy constructor. It compiled fine and the struct was being well-copied where operator= or copy constructor were being called.
The advantage is that I could dump a useless part of the code — prone to errors and probably not updated when someone did maintenance adding a field to the struct! — and I see that as a big advantage.
REASON:
Why I don't need the copy-constructor and the = assignment operator now?
Before, the struct had only simple type fields. So they were copiable. Being all of them copiable, makes the struct copiable. When I added the CArray field, this one was no copiable, because CArray derives from CObject, a class that explicilty makes these two functions private:
class AFX_NOVTABLE CObject
{
//...
private:
CObject(const CObject& objectSrc); // no implementation
void operator=(const CObject& objectSrc); // no implementation
//...
}
And CArray, being a class derived from CObject, doesn't do anything to override this behavior, so CArray will inherit it and rendering itself uncopiable. Having added a CArray before making my struct copiable, I was recieving the error:
c:\program files\microsoft visual studio 8\vc\atlmfc\include\afxtempl.h(272) : error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'
c:\program files\microsoft visual studio 8\vc\atlmfc\include\afx.h(554) : see declaration of 'CObject::operator ='
c:\program files\microsoft visual studio 8\vc\atlmfc\include\afx.h(524) : see declaration of 'CObject'
This diagnostic occurred in the compiler generated function 'CArray<TYPE,ARG_TYPE> &CArray<TYPE,ARG_TYPE>::operator =(const CArray<TYPE,ARG_TYPE> &)'
with
[
TYPE=unsigned int,
ARG_TYPE=unsigned int &
]
The std::vector is copiable by its own definition:
// TEMPLATE CLASS vector
template<class _Ty,
class _Ax = allocator<_Ty> >
class vector
: public _Vector_val<_Ty, _Ax>
{ // varying size array of values
public:
typedef vector<_Ty, _Ax> _Myt;
Notice _Myt is a typedef to the vector class itself.
//...
vector(const _Myt& _Right)
: _Mybase(_Right._Alval)
{ // construct by copying _Right
if (_Buy(_Right.size()))
_TRY_BEGIN
this->_Mylast = _Ucopy(_Right.begin(), _Right.end(),
this->_Myfirst);
_CATCH_ALL
_Tidy();
_RERAISE;
_CATCH_END
}
//...
vector(_Myt&& _Right)
: _Mybase(_Right._Alval)
{ // construct by moving _Right
_Assign_rv(_STD forward<_Myt>(_Right));
}
_Myt& operator=(_Myt&& _Right)
{ // assign by moving _Right
_Assign_rv(_STD forward<_Myt>(_Right));
return (*this);
}
//...
}
So, adding a std::vector member field to a struct/class will not require you to implement copying functions inside it, only because of that new field.
I prefer to avoid STL and not to use it because it used to be not so standard when MFC was de-facto standard for about a decade. Also until recent versions of Visual C++ (and "standard" STL), MFC just have better performance.