欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[Effective C++] Rules 17: Store newed objects in smart pointers in standalone statements

程序员文章站 2022-03-11 17:23:18
...
void process(shared_ptr<int> pi, int priority) { }

process(new int(42), getprior());   // error
                                    // shared_ptr<T>的构造函数为explicit,
                                    // 无法进行隐式转换;

process(shared_ptr<int>(new int(42)), getprior()); // may go wrong

在加入了显示的类型转换后,我们通过了编译。但是,这还是可能出错。

之所以会出错的原因,就在于编译器可以对同一条语句的子操作顺序进行调整。

以本例来说,其中包含了三个子操作

  • new int(42)
  • shared_ptr()
  • getprior()

当中new与shared_ptr()初始化的先后顺序是清晰的;

但是getprior()在第几顺位被运行就无从得知。

如果getprior()在第二顺位运行且抛出了异常,那么RAII也就不复存在。

因此,Store newed objects in smart pointers in standalone statements。这样才是正确的打开方式。

shared_ptr<int> sp(new int(42));
process(sp, getprior());