关于auto_ptr的疑问
#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;
int main()
{
auto_ptr<string> p1(new string("I'm p1"));
auto_ptr<string> p2(p1);
cout<<*p1<<":"<<(&p1)<<endl;
cout<<*p2<<":"<<(&p2)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
if (p2.get())
cout<<"p2 is full"<<endl;
}
照理说auto_ptr<string> p2(p1)执行之后,p1应该属于未绑定,所以照理说应该不能够cout<<*p1,但是,程序确能够正常执行,很不解。而且get返回之后是非零值。
但是:
#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;
void f(auto_ptr<string> p)
{
cout<<"f: "<<*p<<endl;
}
int main()
{
auto_ptr<string> p1(new string("I'm p1"));
f(p1);
cout<<*p1<<":"<<(&p1)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
}
程序执行之后报错,无法正常执行。这个大致理解,但是下面这样又不解了
#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;
void f(auto_ptr<string> p)
{
cout<<"f: "<<*p<<endl;
}
int main()
{
auto_ptr<string> p1(new string("I'm p1"));
auto_ptr<string> p2(p1);
f(p1);
cout<<*p1<<":"<<(&p1)<<endl;
cout<<*p2<<":"<<(&p2)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
if (p2.get())
cout<<"p2 is full"<<endl;
}
又可以正常执行并显示结果,很不解。不是说复制或者赋值之后,原来的auto_ptr会重置为未绑定的auto_ptr对象么,但是我试验的结果却不是这样,求解释。
...全文
相关推荐
C/C++中文帮助文档.chm
C++的内存管理也是学习的重点,文档会讲解动态内存分配(new和delete操作符)、智能指针(如unique_ptr、shared_ptr、weak_ptr)以及内存泄漏的避免策略。
C++参考手册.zip
**智能指针(Smart Pointers)**:C++11引入的智能指针(如unique_ptr、shared_ptr、weak_ptr)可以自动管理内存,防止内存泄漏。8.
C++Primer第五版习题答案
**智能指针**:为了解决原始指针可能导致的内存泄漏问题,C++11引入了智能指针,如unique_ptr、shared_ptr和weak_ptr,它们自动管理对象的生命周期。8.
C++ unique_ptr weak_ptr shared_ptr auto_ptr智能指针.doc
auto_ptr 的机制是将对象所有权转移给 auto_ptr,确保只有一个实例拥有内存所有权。
自己实现的auto_ptr
标题中的“自己实现的auto_ptr”指的是用户自行编写的一个智能指针类,模仿了C++标准库中的`std::auto_ptr`。


