Named constructor and inheritance - c++

I'm working on C++ framework and would like to apply automatic memory management to a number of core classes. So far, I have the standard approach which is
class Foo
{
public:
static
shared_ptr<Foo> init()
{
return shared_ptr<Foo>(new Foo);
}
~Foo()
{
}
protected:
Foo()
{
}
};
// Example of use
shared_ptr<Foo> f = Foo::init();
However, the above breaks when I subclass Foo, since even tho init() is inherited, it still returns shared_ptr<Foo> which contains a pointer to instance of Foo.
Can anyone think of an elegant solution to this? Should I perhaps just stick with (semi-)manually wrapping instances of class with shared_ptr? This would also give ability to expose parameterized constructors without declaring new named constructors...
Ie.
template <typename T>
shared_ptr<T> make_shared(T* ptr)
{
return shared_ptr<T>(ptr)
}
// Example
shared_ptr<T>
f1 = make_shared(new Foo()),
f2 = make_shared(new Foo(1,2));

I would try something like this:
template<class T>
class creator
{
public:
static shared_ptr<T> init()
{
return(shared_ptr<T>(new T));
}
};
class A : public creator<A>
{
};
class B : public A, public creator<B>
{
public:
using make_shared<B>::init;
};
// example use
shared_ptr<A> a = A::init();
shared_ptr<B> b = B::init();
But this isn't necessarily saving you a thing compared to standalone template you proposed.
Edit: I missed previous answer, this seems to be the same idea.

I don't understand what this achieves, you don't appear to be getting any extra memory management using this init function than by simply declaring a shared_ptr.
int main( void )
{
shared_ptr<foo> a = foo::init();
shared_ptr<foo> b( new foo );
}
What's the difference. shared_ptr provides the memory management, not anything in init.

It seems that the goal is to make it impossible for users of the classes to call the constructors directly, and only expose a routine which returns shared_ptr's.
But if you want to apply this pattern, you need to replicate it in all the subclasses. The subclasses cannot automatically "inherit" init() so that init() would still call the subclass constructor, because init() is not a virtual method and is called without an object.
I would leave the constructors exposed as usual and just use the standard
shared_ptr<X> x = new X();
This keeps cognitive burden low, is readable, and remains flexible. This is how we program in our company with reference counted objects, anyway.

How about...
template<typename Derived>
class Foo
{
public:
static shared_ptr<Derived> init()
{
return shared_ptr<Derived>(new Derived);
}
~Foo()
{
}
protected:
Foo()
{
}
};
class Bar : public Foo<Bar>
{
};
int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<Bar> b = Foo<Bar>::init();
return 0;
}

Why not introduce a common base with a virtual destructor, inherit all necessary classes from it and simply use new?

It's generally not a good idea to force creation of objects using shared_ptr by hiding the constructors. I'm speaking from personal experience here working with an internal company lib that did exactly that. If you want to ensure people always wrap their allocated objects, just make sure that all arguments and members which store instances of these types expect a shared_ptr or weak_ptr instead of a naked pointer or reference. You might also want to derive these classes from enable_shared_from_this, because in a system where all objects are shared, at some point you'll have to pass the this pointer to one of these other objects' methods, and since they're designed only to accept shared_ptr, you're in pretty bad shape if your object has no internal_weak_this to ensure it isn't destroyed.

You need the static factory function in every type of the entire hierarchy.
class Foo
{
public:
static shared_ptr< Foo > instantiate( /* potential arguments */ )
{
return shared_ptr< Foo >( new Foo( /* potential arguments */ );
}
// blah blah blah
};
class Bar : public Foo
{
public:
static shared_ptr< Bar > instantiate( /* potential arguments */ )
{
return shared_ptr< Bar >( new Bar( /* potential arguments */ );
}
// blah blah blah
};
If you still have any confusion, please search CppCodeProvider on sourceforge and see how its done there.

By the way, in large C++ frameworks it's common to hide the "automatic memory management" from the coder. This lets him write shorter and simpler code. For example, in Qt you can do this:
QPixmap foo() {
QPixmap pixmap(10, 10);
return pixmap;
}
void bar() {
QPixmap a = foo(); // no copying occurs, internal refcount incremented.
QPixmap b = a; // ditto.
QPainter p(&b);
p.drawPoint(5, 5); // data can no longer be shared, so a copy is made.
// at this point 'a' is still unchanged!
p.end();
}
Like many things in Qt, this mimics the Java object model, but it goes further by implementing copy-on-write (which it calls implicit sharing). This is intended to make the API behavior less suprising to C++ coders, who aren't used to having to call clone().
This is implemented via the d-pointer idiom, which kills two birds with one stone - you provide automatic memory management, and you insulate your implementation from the user (pimpl).
You can look at the actual implementation of QPixmap here: qpixmap.cpp, qpixmap.h.

Related

Two phase construction to use shared_from_this() during object creation for derived classes

I have a setup with a base class that inherits from enable_shared_from_this
class Object : public enable_shared_from_this<Object>
{ ... };
I inherit from enable_shared_from_this because I need to call shared_from_this() every so often. In certain derivations of Object, I need to call shared_from_this() from with in the constructor, which can't be done:
class Thing : public Object
{
public:
Thing() : Object(...)
{ doSomething(shared_from_this()); /* error */ }
};
So a work around is two-phase construction.
class Thing : public Object
{
public:
Thing() : Object(...) { }
void Init() { /* safe to call shared_from_this here */ }
};
A valid way to create a Thing object would be:
shared_ptr<Thing> thing = make_shared<Thing>();
thing->Init();
This is not very nice and error prone but at least it works. However, now there's an issue with further inheritance:
class Bling : public Thing
{
public:
Bling() : Thing(...) { ... }
void Init() { /* safe to call shared_from_this here */ }
};
// How do we create a Bling object?
shared_ptr<Bling> bling = make_shared<Bling>();
static_cast<Thing*>(bling.get())->Init(); // horrible
bling->Init();
// Maybe Bling::Init should look like:
// Bling::Init() { Thing::Init(); /* + other stuff */ }
// then we could do:
shared_ptr<Bling> bling = make_shared<Bling>();
bling->Init(); // etc
Is there a safer or cleaner way to do this? For example, API wise its less error prone to make the constructors for Object, Thing and Bling private and use a static Init() function that creates the shared_ptr:
static shared_ptr<Bling> Bling::Init() {
auto bling = make_shared<Bling>();
Bling::init(bling);
return bling;
}
static void Bling::init(shared_ptr<Bling> bling) {
/* chain parent class init */
Thing::init(bling); // sig: Thing::init(shared_ptr<Thing>);
/* do init stuff */
}
// calls Object(), Thing(), Bling(),
// Object::init(), Thing::init(), Bling::init()
auto bling = Bling::Init();
Basically I'm looking for patterns to implement object creation in a way where I can use a shared_ptr to the object during creation. I need to allow for basic inheritance. I would like suggested methods to consider end-user ease of use and developer maintainability.
You probably should not rely on the fact that the user of an object initially always holds it in a shared pointer. Design the class such that objects are allowed on the stack and heap.
How to solve this depends on what you do with the pointer returned by shared_from_this().
The one thing that comes to my mind is that the object registers itself somewhere - i.e. outside of the object. In my opinion it is better to do that outside of the data classes derived from Object. If you have a registry object of class Registry, turn it into a factory (as suggested by David Schwartz):
class Registry;
class Object
{
protected:
Object() = default;
friend Registry;
public:
// ...
};
class Thing : public Object
{
protected:
Thing() = default;
friend Registry;
public:
// ...
};
class Registry
{
vector<shared_ptr<Object>> store;
public:
shared_ptr<Thing> CreateThing()
{
shared_ptr<Thing> newThing = make_shared<Thing>();
newThing->init(); // If you like.
store.push_back(newThing);
return newThing;
}
shared_ptr<Bling> CreateBling();
// ...
};
No need for enable_shared_from_this at all.
Easier to understand.
Responsibilities clear.
Easily changed such that unregistered Object and Thing objects are allowed. (Scratch the protected constructor and the friend declaration.)
It might already be clear, but just to be sure: I am not in favor of enable_shared_from_this. It makes the assumption, that the object is managed by a shared_ptr at the time shared_from_this() is called. If this is not the case, the "behavior is undefined". If at least it would be an exception or nullptr would be returned...
Such assumptions are ok, when the creation of the initial shared_ptr and the call of shared_from_this() are close to each other in the code (whatever that means). Does anyone have a use case for this? I don`t.

Residing a member of parent class type inside another class

#include <iostream>
class BarParent
{
virtual void fuz()
{
std::cout << "BarParent" << std::endl;
}
};
class BarChild : public BarParent
{
virtual void fuz()
{
std::cout << "BarChild" << std::endl;
}
};
class Foo
{
// ??BarParent bar;??
public:
Foo(BarParent bar);
};
What I seek is to store a copy of BarParent that is passed to the constructor and let it reside in Foo, while still calling the correct virtual function
This is an embedded application: Use of the heap is frown upon. So preferably, no heap
SUMMARY: To the best of knowledge, it cannot be done, becuase of the slicing problem (long story short the compiler cannot determine the size of generic Bar and so on copying it type casts), so polymorphism cannot be achieved. Using templates might be a good idea, however, it defines multiple classes Foo<typename BarType>, as a result, doing a function such as changeBar(BarParent), would not be possible since the compiler would define this as changeBar(BarType) defined only for class Foo<Bartype>. If someone has a better idea, please let me know.
I think i will have to go for heap, or const Barparent and pointers. If the user const_casts, then he is asking for trouble, not my fault!
class Foo
{
BarParent* bar; //or std::unique_ptr<>
public:
Foo(BarParent* barInst):bar(barInst){}
};
This will do what you want it to. You store a pointer to a BarParent object and you can polymorphicaly(is that a word?) call virtual functions using it.
You need to create the copy outside the constructor (on the heap or otherwise), and pass the pointer to it to the foo object constructor. Alternatively you can implement a clone method as discussed at Copying derived entities using only base class pointers, (without exhaustive testing!) - C++
A radically different approach would be to use templates.. it would leave you with a multidudes of foo<> types though.. If you are not going to reassign the bar object, or store all foo in a container, this might be the better option for you, since it doesn't involve the heap
template<typename BarType>
class Foo
{
BarType bar; //pointer not needed any more since we are storing the exact type.
public:
Foo(BarType& barInst):bar(barInst){}
};
There is no way I know of to handle this gracefully without object slicing.
The only way I could think of would be to use pointer, and create a copy when "calling" the Foo constructor:
class Foo
{
BarParent* bar;
public:
Foo(BarParent* b) : bar(b) {}
};
BarChild child;
Foo myFoo(new BarChild(child));

Self-returning class?

I was wondering if (in C++) you can instantiate a class (class foo) then have said class return the already instantiated object. (foo::instance())
In other words, can I have a class return it's-self via it's own methods? I want to be able to create a class (i.e. class foo) early in my program so it is already setup and ready to go. Then, farther down the line, I want to be able to call functions from that class without having to pass that object as an argument to my calling function. Can I do something like so:
MyClass::ReturnSelf()->foo();
or
MyClass::ReturnSelf().foo();
EDIT: I just realized this might be a little unclear. I want to be able to have another class call this "self-returning" method so it can use the already instantiated object's methods and members without creating a new object.
Congrats, you've discovered the singleton pattern. Quite a caveat, if you didn't already know it.
struct X
{
static X& instance()
{
static X x;
return x;
}
void foo();
};
and call the method as:
X::instance().foo();
Of course, you could also make the method static, if that's an option, and call it directly:
X::foo(); //this requires foo to be declared static
The effect of returning the instance from methods can also be used for method chaining:
struct Element
{
Element& setColor() { return *this; }
Element& setWidth() { return *this; }
};
Element e;
e.setColor().setWidth();
A static member function usually does the trick:
struct Foo
{
static Foo & special_instance()
{
static Foo impl; // Alarm bells: This is a global state!
return impl;
}
// ...
};
Usage (from anywhere in the code):
Foo & f = Foo::special_instance();
// ...
You have the additional option of making all the constructors of the class private so that this sort of object creation is the only option. This is generally awkward design, but there may be situations where it is useful. Just be mindful whether you're modeling your problem correctly or whether you might get away with something simpler.
I just realized this might be a little unclear. I want to be able to have another class call this "self-returning" method so it can use the already instantiated object's methods and members without creating a new object.
define a class-variable in class foo of type foo that you can return in static class method instance(). You may also try to give it type *foo and set it up with a pointer on first ctor, wich makes it possible to derive from your class.
class Foo
{
# class variable pointing to first instance
static foo* pFoo = null;
# constructor, sets pointer to first instance
Foo()
{
if (!pFoo) pFoo = this;
/* ... */
}
# static class method returning instance
static foo* instance() {return pFoo;}
}

interchangeable derived class method from base class c++

i am pretty sure this is a simple question for a long time c++ user, this should be a pattern or the problem should be solved in any other way but given i am Python developer and a total novice with c++ i don't know how it's usually done.
Suppose that i have a class where i want to store a pointer to an object that can be of 1 of two different classes that respects an interface, for example:
class AllPlayers
{
public:
virtual void play();
};
class VlcPlayer: public AllPlayers
{
public:
virtual void play();
};
class Mplayer: public AllPlayers
{
public:
virtual void play();
};
class MyMediaPlayer
{
public:
MyMediaPLayer(int playerType);
AllPlayers m_player;
};
MyMediaPlayer::MyMediaPlayer(int PlayerType)
{
if (PlayerType == 0) {
VlcPlayer tmp_player;
m_player = static_cast<AllPlayers> (tmp_player);
}
else {
Mplayer tmp_player;
m_player = static_cast<AllPlayers> (tmp_player);
}
}
MyMediaPlayer test(0);
test.play();
First, i know this would not work and that it seems pretty normal why but how could i get this effect? i would like to have a member of a class for what i am going to use ever the same methods, implemented using a interface and i would like to avoid trying to cast to every of the derived classes every time i am going to use one of his methods.
C++ is value-based, i.e., if you create an object of a given type you really have an object of this type. This doesn't play nicely with dynamic polymorphism. To get dynamic polymorphism you use a pointer or a reference to the actual object. To also get the life-time straight you typicslly allocate the corresponding object on the stack (make sure your base class has a virtual destructor if you ever release an object of a derived type using a pointer to the base). With this, you should be all set: just call a virtual function of the base class through a pointer to rhe base: When you overridethe function in the derived class this is the function which is called.
If you write
AllPlayers m_player;
that is going to be an instance of AllPlayers and cannot be an instance of a class that derives from it.
You should instead use a pointer and allocate the class on the stack.
For example:
class MyMediaPlayer
{
public:
MyMediaPLayer(int playerType);
~MyMediaPLayer();
AllPlayers m_player;
};
MyMediaPlayer::MyMediaPlayer(int PlayerType)
{
if (PlayerType == 0) {
m_player = new VlcPlayer;
}
else {
m_player = new Mplayer;
}
}
MyMediaPlayer::~MyMediaPlayer()
{
if (0 != m_player) {
delete m_player;
m_player = 0;
}
}
As suggested by #xception use of unique_ptr may relieve you from having to write code to deallocate the instance.
As correctly pointed out by #DietmarKühl you should always declare a virtual destructor in a root class (a base class that does not itself derives from some other class) as is the case with AllPlayers.
class AllPlayers
{
public:
virtual ~AllPlayers();
virtual void play(); // note: this should probably be pure virtual.
};
The reason this will not work is colloquially known as Object Splicing. (Or, for those Harry Potter readers out there, Object Splinching)
Let's look at an example:
class Foo
{
public:
int bob;
float fred;
// Foo(const Foo& otherfoo); // implicit copy constructor
};
class Bar : public Foo
{
public:
double gabe; // gabe newell is fat
char steve; // steve jobs is thin
// Bar(const Bar& otherbar); // implicit copy constructor
};
int main()
{
Foo f;
Bar b;
f.bob = 10;
f.fred = 1.5;
b.bob = 15;
b.fred = 2.5;
b.gabe = 1.77245385091; // sqrt(pi)
b.steve = -4;
f = Foo(b);
return 0;
}
This is legal and valid. Problem is, the implicit copy constructor of Foo is called, and Foo's copy constructor knows nothing about what a Bar is. Only that it contains everything a Foo has, and some extra irrelevant crap. Because of this, only the Foo's data gets preserved; the data unique to the Bar gets spliced off.
It's important to note that this is DEFINED BEHAVIOR: it's doing EXACTLY WHAT YOU TELL IT TO. Casting between a subclass of a base class and a base class is implicit. Furthermore, the behavior of the copy constructor is implicit.
It's also important to note that, under the hood, C++ pointers and references work in the same way. It's perfectly sane to pass the Bar to Foo's copy constructor by reference, this pass by reference does not produce a copy of the object. It's the same as working with a pointer.
The actual splicing takes place as a direct result of the copy constructor biting off more than it can chew. It gets an object with more state than it expected, and its only choice is to ignore the extra state.
With python, this doesn't happen because everything is implicitly stored as a reference type. Since you only work with references (the objects themselves are abstracted away), you never have the opportunity to accidentally splice an object.

Passing dependency to wrapper object via its constructor

I have the following test:
TestGet(): _interface(), _db(_interface)
{
_interface.get = mockGet;
}
which is used when testing this class:
class DB: public IDB
{
public:
explicit DB(Interface_T& interface):
_interface(interface)
{
}
...
private:
Interface_T _interface;
};
Interface_T is a C interface implemented in a struct and passed to me from a C api. I wish to use the DB class as a wrapper around the C interface.
Notice however that DB copies the interface object to its member _interface. Therefore the line:
_interface.get = mockGet;
has no effect from the DB objects point of view although this was the intention when I wrote the test class. How would you rewrite TestGet() to remedy this error? How would you present to the client of the DB class that it copies the value passed to it?
Presuming that your intention is for TestGet to set a member on the Interface_T object used by DB, you can:
A. Defer construction of DB:
TestGet(): _interface(), _db(NULL)
{
_interface.get = mockGet;
// Using a raw pointer here for minimalism, but in practice
// you should prefer a smart pointer type.
_db = new DB(_interface);
}
B. If you have control over the Interface_T class, you could add a constructor that initializes Interface_T::get directly. Then you could do:
TestGet(): _interface(mockGet), _db(_interface)
{
}
C. If you have control over the DB class, you could change it to share ownership of the supplied Interface_T (e.g. through boost::shared_ptr), add a constructor as in B, or add an accessor to its internal Interface_T member.
So you need the interface to be correct by the time the db get's constructed. Well, it's easy. Just create appropriate interface in a function and pass the result to the constructor:
Interface_T makeMockInterface()
{
Interface_T interface;
// I presume you will first use the C API to initialize it and than
interface.get = mockGet;
}
TestGet() : _db(makeMockInterface())
{
}
The Interface_T is returned by value from makeMockInterface, but since the underlying machine code actually returns objects by copying them to caller-provided space, most compilers will actually elide the copy and construct the object in the caller-provided space directly (this is explicitly allowed by standard).
The TestGet class does not need to have separate _interface member, because the _db contains it and they would not be shared anyway, so no point.
Edit: The DB constructor takes non-const reference, even though all it does is it copies the object and const reference is good enough for that. Fixing the constructor would be preferable, but if it's not an option, I'd cast it to non-const. That either needs two casts:
TestGet() : _db(const_cast<Interface_T &>(static_cast<const Interface_T &>(makeMockInterface())))
or a trivial template helper:
template <typename T>
T &lvalue_cast(const T &v) { return const_cast<T &>(v); }
TestGet() : _db(lvalue_cast(makeMockInterface()))
Since the temporary actually is mutable, just does not bind to non-const references as a safeguard, both are well defined.
This is based on Jan Hudec comment above:
class TestGet : public ::testing::Test
{
protected:
TestGet()
: _db(interfaceFactory())
{
}
Interface_T interfaceFactory()
{
Interface_T interface;
_interface.get = mockGet;
return interface;
}
DB _db;
};
I like this clean approach.
There are several ways, all including some kind of inversion of control.
My favourites are :
pass the object to the constructor using the reference to the interface
use the factory pattern to create the object, and return some kind of shared pointer (using interface again)
Something like this (assuming you have base abstract class):
struct Interface
{
virtual ~Interface(){}
virtual void foo() = 0;
};
struct Derived : public Interface
{
void foo(){}
};
struct A
{
A ( std::shared_ptr< Interface > obj_ ) : obj( obj_ )
{}
std::shared_ptr< Interface > obj;
};
//...
A myA( std::shared_ptr< Interface >( new Derived ) );
// ..
The above example is with passing to the constructor.