Using std::unique_ptr in an exported class - c++

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?

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.

Related

Free functions vs singleton vs static class members [duplicate]

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Interface for library c++

I need to create simulation of parabolic flight of bullet(simple rectangle), and one of conditions is to make all calculation inside self-made library and to create for it interface(abstract class).
Am confused how to implement this:
Make fully abstract class and couple of functions(not methods in
class) that will use class through "get()" and "set()"?
Make class with all calculations implemented in his methods, and just
make one "draw" method pure virtual?
I'm using WinAPI, and all graphics through GDI
and will be really appreciate for any help
One of the purposes you create classes for is to separate all unrelative data and operations to the different classes.
In your case one part is calculations and the other part is result layout.
So, the best way to implement it is to define a class which provides all calculations and access to results and implement the drawing function, which will use the object of your calculation class.
Thus, it will be able to use your calculations in other environment (for example, in some your other project) without any code changing, which is natural. It will provide portability of your platform-independent caclulation code.
And the layout part, which is platform-dependent, should be implemented separatly, using just interface, which is provided by the calculation class.
class Trajectory
{
public:
// Constructor, computation call methods
// "GetResult()" function,
// which will return trajectory in the way you choose
...
private:
// computation functions
};
// somewhere else
void DrawTrajectory(Trajectory t)
{
// here is a place for calling all winapi functions
// with data you get using t.GetResult()
}
If abstract class is required you should inherit Trajectory class from an abstract class,
where you will define all functions you have to call.
In this case
//
class ITrajectory
{
public:
// virtual /type/ GetResult() = 0;
// virtual /other methods/
};
class Trajectory : public ITrajectory
{
// the same as in previous definition
};
void DrawTrajectory(ITrajectory T)
{
// the same as in previous definition
}
When you are talking about Windows, libraries, and abstract classes as interfaces, I wonder if you are thinking of sharing classes between DLLs.
There is a declspec(dllexport) keyword, but using this on classes and/or class members is bad. You end up with all your library code closely coupled and completely dependent on using the same compiler version and settings for everything.
A much better option, which allows you to upgrade compiler for one DLL at a time, for instance, is to pass interface pointers. The key here is that the consumer of the library knows nothing about the class layout. The interface doesn't describe data members or non-virtual functions which might get inlined. Only public virtual functions appear in the interface, which is just a class defined in the public header.
The DLL has the real implementation which inherits from the interface. All the consumer has is the virtual function table and a factory (plain old C-compatible function) which returns a pointer to a new object.
If you do that, you can change the implementation any way you like without changing the binary interface which consumers depend on, so they continue to work without a recompile. This is the basis of how COM objects work in Windows.

What is this design pattern? How to use it?

Suppose I have class like this (simplified):
class Foo_p;
class Foo
{
private:
Foo_p *p;
public:
Foo();
/* methods, etc... */
};
This class is a part of an API.
The Foo_p is all the private parts of the class, which are not
declared in the class Foo itself as usual, but rather in a separate forward-declared class that is only used by the underlying implementation not visible on the outside.
I've seen this pattern used in a couple of projects, is there a name for it?
Also, how do I use it properly (e.g. exception safety, etc.)? Where should the actual implementation go? In class Foo, as usual, only using Foo_p for storage of data, or in the Foo_p class with Foo being just a wrapper?
That is the pimpl idiom
See
Handle/Body Idiom - close cousin and the seminal idea for pimpl EDIT Found an online copy of this original James Coplien talk
GotW #100: Compilation Firewalls (Difficulty: 6/10)
GotW #101: Compilation Firewalls, Part 2 (Difficulty: 8/10) for the most recent on this
This is known is PIMPL. private/pointer-to-private implementation. The class, Foo_p, your class would have been is implemented privately and accessed through a pointer to it so that rather than displaying the true class to clients, they only get to see the public interface you chose to expose. It essentially abstracts away from the header the vestiges of implementation detail present in the protected and private members.
I've found it unwieldy in VC++- it breaks code completion. It is useful if you are very sure of your implementation and don't want the private and protected members on display in the header.
I put the actual implementation of class Foo_p in the cpp file for class Foo, although this may have been the cause of the code-completion breaking, at least I don't have to run the risk of the class being reused by inclusion of its header.
It's a d-pointer which is a type of opaque-pointer. Similar to the PIMPL idiom.
One type of opaque pointer commonly used in C++ class declarations is
the d-pointer. The d-pointer is the only private data member of the
class and points to an instance of a struct. Named by Arnt Gulbrandsen
of Trolltech, this method allows class declarations to omit private
data members, except for the d-pointer itself.[6] The result is that
more of the class' implementation is hidden from view, that adding new
data members to the private struct does not affect binary
compatibility, and that the header file containing the class
declaration only has to #include those other files that are needed for
the class interface, rather than for its implementation. As a side
benefit, compiles are faster because the header file changes less
often. The d-pointer is heavily used in the Qt and KDE libraries.
https://en.wikipedia.org/wiki/Opaque_pointer#C.2B.2B

C++, static vs. namespace vs. singleton

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Exporting C++ classes from DLL

I came across this article on Code Project that talks about using an abstract interface as an alternative to exporting an entire class from a C++ DLL to avoid name mangling issues. The author has a Release() method in his interface definition that is supposed to be called by the user to free the class object's resources after using it. To automate the calling of this method the author also creates an std::auto_ptr<T>-like class that calls the Release() method before deleting the object.
I was wondering whether the following approach would work instead:
#include <memory>
#if defined(XYZLIBRARY_EXPORT) // inside DLL
# define XYZAPI __declspec(dllexport)
#else // outside DLL
# define XYZAPI __declspec(dllimport)
#endif // XYZLIBRARY_EXPORT
// The abstract interface for Xyz object.
// No extra specifiers required.
struct IXyz
{
virtual int Foo(int n) = 0;
//No Release() method, sub-class' destructor does cleanup
//virtual void Release() = 0;
virtual ~IXyz() {}
};
// Factory function that creates instances of the Xyz object.
// Private function, do not use directly
extern "C" XYZAPI IXyz* __stdcall GetXyz_();
#define GetXyz() std::auto_ptr<IXyz>( GetXyz_() )
Of course, GetXyz() can be a global function defined in the header instead of a #define. The advantage to this method would be that we don't need to cook up our own derivative of auto_ptr that calls the Release() method.
Thanks for your answers,
Ashish.
by doing this, you risk calling delete (in your process, within auto_ptr's destructor) on an object that is not created by the matching call to new() (that is done inside the factory function, hence inside the dll). Trouble guaranteed, for instance when your dll is compiled in release mode while the calling process in debug mode.
The Release() method is better.
This is exactly how COM works. Avoiding re-inventing this wheel if you already target the Win32 API. Using smart pointers to store COM interface pointers is very common in Windows programming, their destructor calls the Release() method. Take a peek at the MSDN docs for _com_ptr_t and CComPtr for ideas.
The restriction you face if this is a public API is the CRT that the different modules will be linked against and that the CRT that creates the object also needs to be the one to delete it.
There will be a mess if you don't choose the right CRT
Anything sharing memory management should use CRT (or other memory allocation) as external lib - ie. MSVC: Multi-threaded DLL (/MD)
Given that, then there is not even a need for the subclass to achieve your purpose.