I have a class in my library which I want to expose to the users. I don't want to expose the whole class as I might want to make a binary incompatible changes later. I am confused with which of the following ways would be best.
Case 1:
struct Impl1;
struct Handle1
{
// The definition will not be inline and will be defined in a C file
// Showing here for simplicity
void interface()
{
static_cast<Impl1*>(this)->interface();
}
}
struct Impl1 : public Handle1
{
void interface(){ /* Do ***actual*** work */ }
private:
int _data; // And other private data
};
Case 2:
struct Impl2
struct Handle2
{
// Constructor/destructor to manage impl
void interface() // Will not be inline as above.
{
_impl->interface();
}
private:
Impl2* _impl;
}
struct Impl2
{
void interface(){ /* Do ***actual*** work */ }
private:
int _data; // And other private data
};
The Handle class is only for exposing functionality. They will be created and managed only inside the library. Inheritance is just for abstracting implementation details. There won't be multiple/different impl classes. In terms of performance, I think both will be identical. Is it? I am thinking of going with the Case 1 approach. Are there any issues that needs to be taken care of?
Your second approach looks very much like the compilation firewall idiom (sometimes known as the PIMPL idiom).
The only difference is that in the compilation firewall idiom, the implementation class is usually (but not always) defined as a member. Don't forget the constructor
(which allocates the Impl) and the destructor (which frees it). Along with the copy constructor and assignment operator.
The first approach also works, but it will require factory functions to create the objects. When I've used it, I've simply made all of the functions in the Handle pure virtual, and let the client code call them directly.
In this case, since client code actually has pointers to your object (in the compilation firewall idiom, the only pointers are in the Handle class itself), and the client will have to worry about memory management; if no cycles are possible, this is one case where shared_ptr makes a lot of sense. (The factory function can return a
shared_ptr, for example, and client code may never see a raw pointer.)
Related
I have a class e.g.:
class Vehicle {
public:
Vehicle(int handle);
// Methods that use the handle e.g.:
Color getColor() {
return VEHICLE::GET_COLOR(handle);
}
protected:
int handle;
};
I don't know if that example makes sense to you, but I built several wrapper classes around those handles to get a more OOP style of coding.
So my question now is, how much overhead is there when I pass a Vehicle object over just passing the vehicle handle to other methods?
If you split your class in a header and source file and use it in other compilation units there will be a sligth overhead due to the call to the constructor.
To solve this, the definition of your constructor has to be placed within your header file, so that the compiler can inline it.
You can do this with either changing your class declaration:
class Vehicle {
public:
Vehicle(int handle)
: handle(handle)
{
}
...
or by putting the definition inside your headerfile and decorating it with the inline keyword.
class Vehicle {
public:
Vehicle(int handle);
...
}
inline Vehicle::Vehicle(int handle)
: handle(handle)
{
}
Notice that there is no gurantee that your function will be inlined, but probably every major compiler out there will be able to do it.
Also notice, that additional work in your constructor, e.g handle - 1, will also very likely result in a overhead.
If your class is polymorphic or bigger, there might be additional overhead.
An optimizing compiler would ensure that there is no overhead for such simple call forwards. The core class (used by wrapper) should ideally be in same module (DLL/SO), otherwise linker/optimizer may be of little help.
However, for such thin wrappers around core class, even in shared-library scenario, the compiler would simply call the core method, eliminating the wrapper class method from call site.
I have two classes that are used in a project. One class, Callback, is in charge of holding information from a callback. Another class, UserInfo, is the information that is exposed to the user. Basically, UserInfo was supposed to be a very thin wrapper that reads Callback data and gives it to the user, while also providing some extra stuff.
struct Callback {
int i;
float f;
};
struct UserInfo {
int i;
float f;
std::string thekicker;
void print();
UserInfo& operator=(const Callback&);
};
The problem is that adding members to Callback requires identical changes in UserInfo, as well as updating operator= and similarly dependent member functions. In order to keep them in sync automatically, I want to do this instead:
struct Callback {
int i;
float f;
};
struct UserInfo : Callback{
std::string thekicker;
void print();
UserInfo& operator=(const Callback&);
};
Now UserInfo is guaranteed to have all of the same data members as Callback. The kicker is, in fact, the data member thekicker. There are no virtual destructors declared in Callback, and I believe the other coders want it to stay that way (they feel strongly against the performance penalty for virtual destructors). However, thekicker will be leaked if a UserInfo type is destroyed through a Callback*. It should be noted that it is not intended for UserInfo to ever be used through a Callback* interface, hence why these classes were separate in the first place. On the other hand, having to alter three or more pieces of code in identical ways just to modify one structure feels inelegant and error-prone.
Question: Is there any way to allow UserInfo to inherit Callback publicly (users have to be able to access all of the same information) but disallow assigning a Callback reference to a UserInfo specifically because of the lack of virtual destructor? I suspect this is not possible since it is a fundamental purpose for inheritance in the first place. My second question, is there a way to keep these two classes in sync with each other via some other method? I wanted to make Callback a member of UserInfo instead of a parent class, but I want data members to be directly read with user.i instead of user.call.i.
I think I'm asking for the impossible, but I am constantly surprised at the witchcraft of stackoverflow answers, so I thought I'd ask just to see if there actually was a remedy for this.
You could always enforce the 'can't delete via base class pointer' constraint that you mentioned (to some extent) by making the destructor protected in the base class:
i.e.
// Not deletable unless a derived class or friend is calling the dtor.
struct Callback {
int i;
float f;
protected:
~Callback() {}
};
// can delete objects of this type:
struct SimpleCallback : public Callback {};
struct UserInfo : public Callback {
std::string thekicker;
// ...
};
As others have mentioned, you can delete the assignment operator. For pre-c++11, just make an unimplemented prototype of that function private:
private:
UserInfo& operator=(const Callback&);
struct UserInfo : Callback {
...
// assignment from Callback disallowed
UserInfo& operator=(const Callback&) = delete;
...
};
Note that the STL features a lot of inheritance without a virtual destructor. The documentation explicitly states that these classes are not designed to be used as base classes.
some examples are vector<>, set<>, map<> ....
Another approach is to consider private inheritance while providing an accessor method to reveal the Callback (in which case you may as well use encapsulation which is cleaner).
Yes, there's trickery you can use to keep the members in sync and update operator= automatically. It's ugly though, involving macros and an unusual way of using an include file.
CallBackMembers.h:
MEMBER(int, i)
MEMBER(float, f)
Elsewhere:
struct Callback {
#define MEMBER(TYPE,NAME) TYPE NAME;
#include "CallbackMembers.h"
#undef MEMBER
};
struct UserInfo {
#define MEMBER(TYPE,NAME) TYPE NAME;
#include "CallbackMembers.h"
#undef MEMBER
std::string thekicker;
void print(); // you can use the macro trick here too
UserInfo& operator=(const Callback& rhs)
{
#define MEMBER(TYPE,NAME) NAME = rhs.NAME;
#include "CallbackMembers.h"
#undef MEMBER
return *this;
}
};
There is no way to meet ALL the criteria you want.
Personally I think your idea to make it a member and then use user.call.i is the best and most clear option. Keep in mind that you write code that uses this just once, but you make up for it in maintainability (since your UserData never has to change) and readability (since it's 100% transparent to the end-use which attribute are part of the callback data and which are auxiliary).
The only other option that might make sense is to use private inheritance instead, and using the attribute or function into UserData. With this you still have to add one using when new data is added to callback, but you get your desired user.i syntax for clients.
I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.
When implementing singletons in c++, I see two ways to store implementation data :
(A) put all implementation data in the private section and implement class as usual
(B) "pimpl idiom for singletons" : hide implementation data by placing it to the 'Impl' structure, which can be defined in the implementation file. Private section contains only a reference to the implementation structure.
Here is a concept code to clarify what I mean by (A) and (B) implementation options :
(A) SingletonClassMembers.hpp :
// a lot of includes required by private section
#include "HelperClass1.hpp"
#include "HelperClass2.hpp"
// some includes required by public section
// ...
class SingletonClassMembers {
public:
static SingletonClassMembers& getInstance();
// public methods
private:
SingletonClassMembers ();
~SingletonClassMembers();
SingletonClassMembers (const SingletonClassMembers&); //not implemented
SingletonClassMembers& operator=(const SingletonClassMembers&); //not implemented
HelperClass1 mMember1;
HelperClass2 mMember2; //and so on
(A) SingletonClassMembers.cpp :
#include "SingletonClassMembers.hpp"
SingletonClassMembers& getInstance() {
static SingletonClassMembers sImpl;
return sImpl;
}
(B) SingletonHiddenImpl.hpp :
// some includes required by public section
// ...
class SingletonHiddenImpl {
public:
static SingletonHiddenImpl& getInstance();
// public methods
private:
SingletonHiddenImpl ();
~SingletonHiddenImpl ();
SingletonHiddenImpl (const SingletonHiddenImpl&); //not implemented
SingletonHiddenImpl& operator=(const SingletonHiddenImpl&); //not implemented
struct Impl;
Impl& mImpl;
};
(B) SingletonHiddenImpl.cpp :
#include "SingletonHiddenImpl.hpp"
#include "HelperClass1.hpp"
#include "HelperClass2.hpp"
struct SingletonHiddenImpl::Impl {
HelperClass1 member1;
HelperClass2 member2;
};
static inline SingletonHiddenImpl::Impl& getImpl () {
static Impl sImpl;
return sImpl;
}
SingletonHiddenImpl::SingletonHiddenImpl ()
: mImpl (getImpl())
{
}
So, using (B) approach, you can hide implementation details better and (unlike pimpl idiom for ordinary classes) there`s no performance loss. I can`t imagine conditions where (A) approach would be more appropriate
The question is, what are the advantages of storing implementation data as class members (A) ?
Thank you
Using case A has following benefits:
You reduce dependency between classes SingletonClassMembers and SingletonHiddenImpl.
You don't need to create configurator pattern in class SingletonClassMembers if you trying avoid restriction on (1) by dependency injection
This case is weak, but anyway: it is simple to maintenance single class
In multithreading environment you will need to support both class synchronization mechanism, while in single class only single locks is needed.
As you only have one instance of your singleton, you can actually move your helpers into the implementation class as "static" there without requiring them to be private inside the header. Of course you don't want to initialise them until you start your class so you would use some kind of smart-pointer, could be auto_ptr here or boost::scoped_ptr, or a pointer with boost::once initialisation (more thread-safe) with deletes in your singleton's destructor.
You can call this model C and probably has the best of both worlds as you completely hide your implementation.
As is the case with any singleton, you need to be extra careful not to throw in your constructor.
When considering efficiency with pimpl, it is not the heap that causes overhead, but the indirection (done by delegation). This delegation typically isn't optimized out (at least not at the time I was considering this ;-)), so there is not a big gain apart from the startup (1 time) penalty for creating the impl. (BTW, I didn't see any delegation functions in your example)
So I don't see that much difference in using pimpl in normal classes or in singletons. I think in both case, using pimpl for classes with limited interface and heavy implementation, it makes sense.
I've been spoiled using Java in the last few months! I have a C++ project where I would like to decouple a class interface (.h file) from its implementation details. But the class's member fields have to be in its declaration, and it seems like I have this unavoidable dependency linking if I want to tweak the class's member fields.
I know one way to do this is using polymorphism + class inheritance (make the interface a base class, make the implementation a derived class), but if I remember right, that requires virtual functions, which are something I would like to avoid -- this is on a DSP and it's advantageous not to get too "C++-y" with things.
any suggestions?
You want the PIMPL idiom.
You know, I thought about this and your objection to PIMPL for a bit.
I have an ugly hack I use sometimes for cases like this, where I resent paying the indirection penalty. Though usually my complaint is with calling new, and not with the pointer dereference. I present my ugly hack thusly:
// IHaveOpaqueData.h
class IHaveOpaqueData {
public:
// To make sure there are no alignment problems, maybe ::std::uin64_t
typedef maximally_aligned_type_t internal_data_t[32]; // Some size I hope is big enough
void iCanHazMemberFunction();
// ...
private:
internal_data_t data;
};
// IHaveOpaqueData.cpp
#include <boost/static_assert.hpp>
namespace { // Hide it in an anonymous namespace
struct RealData {
int icanhazmembervariable_;
double icanhazdoublevariable_;
};
BOOST_STATIC_ASSERT(sizeof(RealData) < sizeof(IHaveOpaqueData::internal_data_t);
}
void IHaveOpaqueData::iCanHazMemberFunction()
{
// Use a reference to help the optimize make the right decision
RealData &datathis = *(reinterpret_cast<RealData *>(&(this->data)));
datathis.icanhazmembervariable_ = datathis.icanhazdoublevariable_;
}
Yes, this is ugly. BOOST_STATIC_ASSERT (or if you have a C++[01]x compiler the static_assert keyword) helps make it not be a total disaster. There may be a clever way to use unions to mitigate some of the twitchiness I have over alignment issues as well.
Use the pimpl idiom. Read here: http://www.devx.com/cplus/Article/28105/0/page/3
It will help decoupling the implementation from the interface and will reduce (to a minimum) all compilation dependencies. You can even avoid virtual functions.
Here's an old idea :) - opaque data type plus a set of functions, i.e. "there and back [to C] again":
// oi.hpp
namespace oi // old idea
{
struct opaque; // forward declaration
void init( opaque& ); // ctor
void fini( opaque& ); // dtor
int get_foo( const opaque& ); // getter
void set_foo( opaque&, int ); // setter
}
// oi.cpp
namespace oi
{
struct opaque // definition
{
int foo_; // data members
// ...
};
// function definitions
}
The runtime cost of accessing the structure via reference is probably the same as with pimpl, so this is probably an inferior solution given some important idioms like RAII cannot be used.