如果默认的构造和拷贝(或移动)的分配很便宜,只需使用:
myclass myobject;
if (set1)
myobject = myclass(1, 2);
else
myobject = myclass(3);
myobject.operation();
如果可以接受在堆上分配的事情,使用指针:
std::unique_ptr<myclass> myobject;
// const std::auto_ptr<myclass> in C++03 (it's fine as long as you keep it unique)
if (set1)
myobject.reset(new myclass(1, 2));
else
myobject.reset(new myclass(3));
myobject->operation();
如果你必须将它分配给堆栈,除了使用新的位置(或者改变构造函数来接受两种可能性)之外,我还是没有看到。
#include <new>
char myobject_buffer[sizeof(myclass)];
myclass* ptr;
if (set1)
ptr = new (myobject_buffer) myclass(1, 2);
else
ptr = new (myobject_buffer) myclass(3);
ptr->operation();
...
ptr->~myclass(); // <-- use RAII to call this for exception safety
“set 1”是什么意思?这是不正确的c + +语法,是那些相同类型的不同变量?不同的类型?不兼容的类型?模糊的转换序列?你尝试了什么,并得到一个错误?什么错误? – PlasmaHH 2012-02-10 10:46:59