ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 关于auto_ptr的问题

2019-08-26 12:04:32  阅读:124  来源: 互联网

标签:auto-ptr c


假设,我们有以下代码

auto_ptr<T> source() 
{
  return auto_ptr<T>( new T(1) );
}
void sink( auto_ptr<T> pt ) { }
void f()
{
  auto_ptr<T> a( source() );
  sink( source() );
  sink( auto_ptr<T>( new T(1) ) );
  vector< auto_ptr<T> > v;
  v.push_back( auto_ptr<T>( new T(3) ) );
  v.push_back( auto_ptr<T>( new T(4) ) );
  v.push_back( auto_ptr<T>( new T(1) ) );
  v.push_back( a );
  v.push_back( auto_ptr<T>( new T(2) ) );
  sort( v.begin(), v.end() );
  cout << a->Value();
}
class C
{
public:    /*...*/
protected: /*...*/
private:   /*...*/
  auto_ptr<CImpl> pimpl_;

我感兴趣:什么是好的,什么是安全的,什么是合法的,什么不在这个代码中?
因为我知道auto_ptr是,例如下面的代码

#include <iostream>
#include <memory>
using namespace std;

int main(int argc, char **argv)
{
    int *i = new int;
    auto_ptr<int> x(i);
    auto_ptr<int> y;

    y = x;

    cout << x.get() << endl; // Print NULL
    cout << y.get() << endl; // Print non-NULL address i

    return 0;
}

此代码将为第一个auto_ptr对象打印一个NULL地址,为第二个打印一个非NULL地址,表明源对象在赋值(=)期间丢失了引用.不应删除示例中的原始指针i,因为它将被拥有该引用的auto_ptr删除.实际上,new int可以直接传递给x,从而消除了对i的需求.
我怎样才能确定我的代码中的哪一行是安全的,哪些不是?

解决方法:

vector<auto_ptr<T>> v;
v.push_back(auto_ptr<T>( new T(3) ));
v.push_back(auto_ptr<T>( new T(4) ));
v.push_back(auto_ptr<T>( new T(1) ));

该标准完全禁止这一点.

标签:auto-ptr,c
来源: https://codeday.me/bug/20190826/1729957.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有