指针类型是"阻止"在声明中调用构造函数的唯一方法吗?

man*_*eak 0 c++ pointers

我试图搜索这个,但我没有找到任何答案.我们来看看这个:

class Foo
{
    Foo();
    Bar a; // 'a', the object, gets created (even if I don't want to!)
    Bar* b; // 'b', the pointer, gets created, but the object doesn't
}

Foo::Foo()
{
    a = a(); // I'd like to create 'a' here instead. This just "replaces" it
    b = new Bar(); // 'b', the object, gets created
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以声明一个对象而不创建它吗?或者我总是要使用指针?

Ben*_*ley 5

我的问题是:我可以声明一个对象而不创建它吗?

没有.

或者我总是要使用指针?

没有.指针是一种选择.还有其他的,如boost::optional(std::optional也在标准化过程中).还有智能指针(std::unique_ptrstd::shared_ptr).标准可用的pre-c ++ 11选项比原始指针更易于管理std::vector,您只需添加一个元素.

但你绝对确定你需要这个吗?