【发布时间】:2015-03-28 16:17:43
【问题描述】:
我基本上会编写以下代码。我明白为什么它不能编译了。
A instance; // A is a non-default-constructable type and therefore can't be allocated like this
if (something)
{
instance = A("foo"); // use a constructor X
}
else
{
instance = A(42); // use *another* constructor Y
}
instance.do_something();
有没有办法在不涉及堆分配的情况下实现这种行为?
【问题讨论】:
-
您是否还为
A提供了复制构造函数和赋值运算符?同样对于这种情况,您最好为您的类属性设置 getter/setter 函数,并使用默认构造函数。 -
最简单的解决方案似乎是使用指针。您是否有理由需要它在堆栈上?
-
将其推入向量中?
-
你不能
A instance("");?
标签: c++ allocation default-constructor