大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
智能指针是其指向对象的拥有者,当智能指针被销毁时,对象也被销毁。
一个对象只可能被一个智能指针拥有。


auto_ptr对对象的拥有权

//pass by value
void TestParaValue(auto_ptr<int> p)
{
    cout
<<boolalpha<<(NULL==p.get())<<endl;
    cout
<<*p<<endl;
}


//pass by reference
void TestParaRef(const auto_ptr<int>& p)
{
    cout
<<boolalpha<<(NULL==p.get())<<endl;
    cout
<<*p<<endl;
}


//return value
auto_ptr<int> TestRet()
{
    auto_ptr
<int> pa(new int(5));
    
return pa;
}


int main()
{
    
{
        auto_ptr
<int> pa(new int(4));                //auto_ptr初始化,pa拥有对象
        cout<<*pa<<endl;

        auto_ptr
<int> pb(pa);                        //auto_ptr初始化,pa将拥有权转交给pb
        cout<<boolalpha<<(NULL==pa.get())<<endl;    //pa里内容为null
        cout<<*pb<<endl;                            //pb拥有对象
        
        auto_ptr
<int> pc = TestRet();                //返回值形式的函数调用,函数内部创建的对象所有权交给pc
        cout<<*pc<<endl;                            //pc拥有对象

        TestParaValue(pb);                            
//传值方式函数调用,pb将拥有权转交给形参,函数返回时形参销毁,对象销毁
        cout<<boolalpha<<(NULL==pb.get())<<endl;    //pb里内容为null
        
        TestParaRef(pc);                            
//传引用方式函数调用
        cout<<boolalpha<<(NULL==pc.get())<<endl;    //pc没有转交拥有权

        auto_ptr
<int> pe;                            //pe内为null    
        
//*pe = 44;                                    //error,向空指针指向的地址赋值

        
const auto_ptr<int> pf(new int (4));        //const auto_ptr
        
//pf = pc;                                    //error, const的auto_ptr所有权不能改变
        *pf = 8;                                    //ok, const的auto_ptr的内容可以改变
    }

    getchar();
    
return 0;
}

auto_ptr的操作
int main()
{
    
{
        auto_ptr
<int> pa(new int(4));                
        cout
<<*pa<<endl;                            //*操作符返回auto_ptr拥有的对象
        cout<<boolalpha<<(NULL==pa.get())<<endl;    //get()返回对象地址
    
        auto_ptr
<int> pb(pa.release());                //release()放弃对象拥有权,返回对象地址
        cout<<boolalpha<<(NULL==pa.get())<<endl;
        cout
<<*pb<<endl;    
        
        pb.reset(
new int(6));                        //重新设置auto_ptr的内容,删除之前的内容
        cout<<*pb<<endl;

    }

    getchar();
    
return 0;
}

posted on 2009-06-19 14:50 大胖 阅读(200) 评论(0)  编辑 收藏 引用 所属分类: STL

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理