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

Are pointer types the only way to "prevent" constructor being called in declaration?

本文关键字:唯一 方法 构造函数 类型 prevent 声明 指针 调用      更新时间:2023-10-16

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

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
}

我的问题是:我可以在不创建对象的情况下声明它吗?还是我总是必须使用指针?

我的问题是:我可以在不创建对象的情况下声明它吗?

不。

还是我总是必须使用指针?

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

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