首页 > 解决方案 > 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 编译器编译。上述输出是预期的行为吗?

标签: c++c++14unique-ptr

解决方案


您的第二个示例实际上并未创建A对象。它只是创建一个未初始化的unique_ptr到一个。A取消引用这样的指针是未定义的行为,编译器可以做它想做的任何事情,但你不能依赖任何特定的行为。示例二是损坏的代码。


推荐阅读