指针类型是"prevent"声明中调用构造函数的唯一方法吗?
Are pointer types the only way to "prevent" constructor being called in declaration?
>我试图搜索这个,但我没有找到任何答案。让我们看看这个:
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_ptr
或std::shared_ptr
(。 比原始指针更易于管理的标准可用 pre-c++11 选项将是一个只添加一个元素的std::vector
。
但是你绝对确定你需要这个吗?
相关文章:
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 函数从唯一代码调用正确的子类方法
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 初始化 C++14 中唯一指针向量的正确方法
- 如果指针的子类的方法对于子类是唯一的,如何访问这些方法?
- 唯一 ptr 将所有权移动到包含对象的方法
- C++11 重载方法,并转发到唯一方法
- 此QChangesCapacityEffect使用是否会导致潜在的内存泄漏?(但这是强制重新喷漆的唯一方法)
- 从数组中删除唯一元素的最有效方法
- 将全局对象初始化为指针是唯一成功的方法
- 递归类型真的是构建不连续的任意大小数据结构的唯一方法吗
- 方法,用于在代码中唯一标识方法调用,以测试调用序列是否未更改
- 基类的指针数组:如何调用唯一的派生类方法
- C++:通过进程id、进程句柄和标题名称从进程中获取唯一窗口的窗口句柄的最佳方法
- 指针类型是"prevent"声明中调用构造函数的唯一方法吗?
- 在 2D 标准::矢量<矢量中查找唯一值的有效方法<double>>
- 宏是强制内联的唯一方法吗?
- 将QObject连接指定为唯一的正确方法是什么
- 条件运算符是在全局作用域中初始化全局变量的唯一方法