unique_ptr
问题:内存管理不当
- C++将内存交给编程者管理,让编程者可以高效的操作内存,提高程序的效率。
- 当然并不是说,所有的内存都可以由编程者操作,例如栈上的内存,就是有C++本身管理。这里所说的可操作内存,大多数时候指堆上的内存,也就是new出来的内存。
- new,用来动态申请内存。new会为调用者,返回一个指向该对象的指针。
- delete,释放/删除动态申请的内存。
- new/delte导致的问题
- new申请资源,使用后,忘记释放资源(内存泄露)。
- new申请资源,使用前,提前释放资源(非法访问)。
for (xxx) {
Object * obj = new Object(xxx);
if (NULL != obj) {
obj->func();
}
}
Object obj = new Object(xxx);
delete obj;
obj->func();
- 对于几百或几千行代码,一般不会有这种误操作的情况。但百万甚至千万行级别的代码,这种问题就很容易出现了。如果出现了,排查起来也比较费时。
解决:unique_ptr
- C++11提供了两种智能指针,shared_ptr和unique_ptr。
- shared_ptr允许多个指针(shared_ptr)指向同一个对象。
- unique_ptr仅允许一个(unique_ptr)指向该对象。
- 同一时刻只能有一个unique_ptr指针,指向给定对象。
- 它提供的release方法,释放它指向的对象的所有权(此时,就可以让另一个unique_ptr指向该对象了)
- reset方法,会直接释放它所指向的对象(相当于delete)。
- reset方法可传入它要指向的新的对象。
- 可以通过std::move,转移指向对象的所有权。
#include <iostream>
#include <memory>
#include <string>
struct Foo
{
Foo(std::string args)
: m_args(args)
{
std::cout << "Foo::Foo::" << m_args << std::endl;
}
~Foo()
{
std::cout << "Foo::~Foo" << std::endl;
}
void whoIam()
{
std::cout << "Foo::whoIam::"<< m_args << std::endl;
}
std::string m_args;
};
void test_one()
{
std::unique_ptr<Foo> p_one(new Foo("me"));
if (NULL != p_one) {
std::unique_ptr<Foo> p_two;
if (NULL == p_two) {
std::cout << "p_tow is null" << std::endl;
}
p_two = std::move(p_one);
p_two->whoIam();
if (NULL == p_one) {
std::cout << "p_one is null" << std::endl;
}
p_one = std::move(p_two);
}
if (NULL != p_one) {
std::cout << "p_one is not null" << std::endl;
}
}
int main()
{
test_one();
return 0;
}