更新中
智能指针
传统指针的问题
内存泄漏,分配的内存没有及时释放,导致在释放这段内存之前就失去了对内存的控制
想法
在栈中删除指针时,指针的内存也被释放
常规指针->有析构函数的对象
智能指针模板
- auto_ptr(C++11摒弃)
- unique_ptr
- shared_ptr
在删除智能指针的同时,析构函数释放内存
头文件 memory
auto_ptr<double> pd(new double)
所有权问题
一个智能指针直接赋值给另外一个
如果是常规指针将指向同一个对象,但智能指针会导致程序试图删除同一个对象两次,这是不能允许的。
-
auto_ptr
auto_ptr的赋值导致所有权转让,放弃对象所有权的指针是一个空指针
-
shared_ptr
程序可以正常运行,创建对象的引用计数,当成员被释放的时候,调用析构函数时,将引用计数降低到0,并释放以前分配的内存
-
unique_ptr
和auto_ptr一样,但是编译会报错
unique_ptr进行赋值时,如果源unique_ptr是一个临时右值,编译器允许这样做,如果会存在一段时间,编译器禁止这样做。
可以使用std::move()函数将unique_ptr赋给另一个
std::make_unique
Constructs an object of type T
and wraps it in a std::unique_ptr.
Constructs a non-array type T
. The arguments args
are passed to the constructor of T
. This overload only participates in overload resolution if T
is not an array type. The function is equivalent to:
unique_ptr<T>(new T(std::forward<Args>(args)...))
std::unique_ptr<T,Deleter>::get
Returns a pointer to the managed object or nullptr if no object is owned.
指针的ownership
What is ownership of resources or pointers?
I don’t think there is a universally accepted, 100% accurate and always-applicable definition, but the most useful definition of ownership I’ve encountered in the context of C++ (and programming in general) is responsibility for cleanup. That is, an owner of a resource is the one who’s responsible for correct cleanup of that resource.
What “resource” and “cleanup” mean depends on context. When the resource is memory dynamically allocated via
new
, cleanup is callingdelete
. When the resource is a file descriptor, cleanup is closing it. And so on.That’s why Plain Old Data cannot express ownership: a POD class must have a no-op destructor, and thus cannot perform any automatic cleanup.
Compare
int *
,std::unique_ptr<int>
, andstd::shared_ptr<int>
. All these types are "a pointer to anint
". But the first one does not represent ownership — you can do anything you want with it, and you can happily use it in ways which lead to memory leaks or double-frees.
std::unique_ptr<int>
represents the simplest form of ownership: it says “I am the sole owner of the resource (= the dynamically allocatedint
). When I get destroyed, I clean it up correctly.” It is designed not to offer a sane way of violating the ownership semantics (e.g. it’s noncopyable).
std::shared_ptr<int>
represents a more complex form of ownership: “I am one of a group of friends who are collectively responsible for the resource. The last of us to get destroyed will clean it up.” Again, there are a few hoops to jump through before you can violate the semantics.