Assume I have a class with different constructors:
class A
{
public:
A(char* string)
{
//...
}
A(int value)
{
//..
}
A a = isTrue() ? A("string") : A(10);
And if a.check()
is a const member function, an alternative may be better:
const A& a = isTrue() ? A("string") : A(10);
The object will be destroyed when the reference a
go out of scope.
Note since C++17, according to the rule of copy elision the copy/move constructor is not required to be accessible for this case; copy elision is guaranteed here.
And since C++17 you can use std::optional, which doesn't cause any dynamic memory allocation. e.g.
std::optional a;
if (isTrue())
{
a.emplace("string");
}
else
{
a.emplace(10);
}
(*a).check();
BTW: A(char* string)
is supposed to be A(const char* string)
.