c++ - 当 std::make_unique 发生什么() 分配给 std::unique_ptr?
问题描述
我对 std::unique_ptr 有一个疑问。
当我们分配没有参数的 std::make_unique() 时,会发生什么?
例如,
struct A {
int a, b;
A() {}
A(int w, int e) : a(w), b(e) {}
};
int main() {
A h(1, 2);
std::unique_ptr<A> hello = std::make_unique<A>();
std::cout << hello->a << std::endl;
}
在上面的代码中,我提到了默认构造函数,我得到了 hello->a 的输出作为垃圾值(随机负值)
但是,当我如下更改结构时,
struct A {
int a, b;
A() {a=0;b=0;}
A(int w, int e) : a(w), b(e) {}
};
hello->a 的结果值为 0。
为什么在使用 std::make_unique() 时默认构造函数不将 int 分配为 0?
解决方案
传递给std::make_unique<A>()
的参数是传递给 的相应构造函数的参数A
。在这里您没有提供任何内容,因此A
将调用默认构造函数。
为什么在使用 std::make_unique() 时默认构造函数不将 int 分配为 0?
未初始化的内置类型的成员留下一个不确定的值。此行为与std::unique_ptr
or无关std::make_unique
;这就是默认初始化内置类型的方式。
初始化它们:
struct A {
int a, b;
A(): a(0), b(0) {}
A(int w, int e) : a(w), b(e) {}
};
推荐阅读
- sql - PSQL 递归添加查询
- php - 创建 PHP yii 框架代码文档
- javascript - 如何在单击按钮中获取动态div的所有索引显示更多jquery
- webpack - 为什么 webpack 缓存卡住了?
- c# - FFMPEG:使用图像序列作为不同的输入
- python - 带有 Tweepy 的 Python Twitter 机器人:mentions_timeline() 接受 1 个位置参数,但给出了 2 个
- python - 如何在 python 中只读取 1 个单词?
- r - 在 R 中更改 mplusModeler 的 STARTS
- c# - Parallel.ForEach 不可能进行漂亮的日志记录?
- javascript - 以本机反应发送电子邮件