Assume I have a class with different constructors:
class A
{
public:
A(char* string)
{
//...
}
A(int value)
{
//..
}
void check() {}
};
Now I want to create an A object on stack, the constructor must be choosed depending on some condition, but there is a problem: the created object is destroyed then we quit {...} block.
bool isTrue() { /*...*/ }
int main()
{
if (isTrue())
{
A a("string");
}
else
{
A a(10);
}
a.check(); //error: 'a' is not defined in this scope
}
Suppose I haven't the copy-constructor or operator=
in the A
class. So how can solve this issue?
http://ideone.com/YsjmnK
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.
BTW:
A(char* string)
is supposed to beA(const char* string)
.If the type has a default constructor, you can default-construct an object, immediately destruct it, and then construct it again with the appropriate constructor via placement-new:
The C++ standard has several examples similar to the above, just search for
.~
and->~
.Note that this is ultra evil. If your code ever gets reviewed, you are probably going to get fired.
You can use the template class:
You can't satisfy all your stated requirements.
If you can get rid of the requirement for the object to be on stack, you could use a pointer.
I had the exact same question a while ago and this is what google helped me find:
Its probably too late for the OP but someone else might hopefully find this useful.