Problem: I have a non-copyable object with two constructors. I need to create an object with one of the constructors and then use it within some common code:-
With a copyable object it would look like this, and be easy:
Object a;
if (condition)
a = Object(p1);
else
a = Object(p2,p3,p4);
a.doSomething();
But, the object is non-copyable, so I’ve had to do this:
boost::scoped_ptr<Object> a;
if (condition)
a = new Object(p1);
else
a = new Object(p2,p3,p4);
a->doSomething();
This feels too complex. Is there a better solutiuon?
Here’s a very terrible hack, assuming
Objectis default-constructible:Don’t use this.
Another option is using a union, but you’ll need to invoke the destructor manually in that setup as well.
A cleaner solution could be achieved with Boost.Optional (using in-place factories). (Thanks to @K-Ballo for digging up the details!)