You can actually do it quite simply, even without C++11 and lambdas:
const MyClass a;
{
MyClass _a;
_a.init();
std::swap(const_cast<MyClass&>(a), _a);
}
The use of const_cast
is admittedly a bit of a hack, but it won't break anything as const
is quite a weak specifier. At the same time, it is quite efficient, as the MyClass
object is only swapped, not copied (most reasonable expensive-to-copy objects should provide a swap
function and inject an overload of std::swap
).
Without the cast, it would require a helper:
struct Construct_Init {
operator MyClass() const
{
MyClass a;
a.init();
return a;
}
};
const MyClass a = Construct_Init();
This can be like this in a function (the Construct_Init
structure needs not be declared at namespace scope), but it is a bit longer. The copy of the object may or may not be optimized away using copy elision.
Note that in both cases, the return value of init()
is lost. If it returns a boolean where true
is success and false
is failure, it is better to:
if(!a.init())
throw std::runtime_error("MyClass init failed");
Or just make sure to handle the errors appropriately.