c++ - c++ 中的 unique_ptr 行为
问题描述
使用 std::unique_ptr 创建对象时的奇怪行为。这里有两个例子:
#include<iostream>
#include<memory>
using namespace std;
class A
{
public:
A() {
throw "EOF";
}
void show()
{
cout<<"A::show()"<<endl;
}
};
int main()
{
try {
unique_ptr<A> p1 = make_unique<A>();
p1 -> show();
} catch(...) {
cout << "Exception" << endl;
}
return 0;
}
输出
Exception
上面的输出看起来很明显。但是,以下代码的输出是奇数。
// C++ program to illustrate the use of unique_ptr
#include<iostream>
#include<memory>
using namespace std;
class A
{
public:
A() {
throw "EOF";
}
void show()
{
cout<<"A::show()"<<endl;
}
};
int main()
{
try {
unique_ptr<A> p1;
p1 -> show();
} catch(...) {
cout << "Exception" << endl;
}
return 0;
}
输出
A::show()
这些示例使用 c++14 编译器编译。上述输出是预期的行为吗?
解决方案
您的第二个示例实际上并未创建A
对象。它只是创建一个未初始化的unique_ptr
到一个。A
取消引用这样的指针是未定义的行为,编译器可以做它想做的任何事情,但你不能依赖任何特定的行为。示例二是损坏的代码。
推荐阅读
- django - django 如何获取序列化器字段的值?
- c# - 使用来自 C# Uno 项目的跨平台 C++ 动态库
- java - 如何停止处理 akka 流中的其他元素?
- python - Spark 上 GRU 网络的分布式训练 - PyTorch 实现
- python - np.where 返回错误的索引
- hibernate - 在 Hibernate Search 中将 @IndexedEmbedded 实体设为只读关系
- javascript - 脚本中的第二个 jQuery 函数不执行
- java - 如何在这段代码中处理空指针异常?
- vba - mailMerge 中的 dataSource.RecordCount
- php - Woocommerce 本地取货加 php 取货日期和时间