C++

C++ (02) 智能指针

Posted by xcTorres on December 17, 2020

因为目前用的地图引擎是用C++写的,现在也要适当的回顾一下C++语言了。

智能指针

在智能指针出现之前,C++ create一个对象用的new返回的是一个指针对象,即使这个函数已经结束了,C++也不会主动帮忙回收该内存。所以得用代码每次手动delete释放内存。但有了智能指针之后,C++就像Java一样,不需要自己手动回收内存了了。所以只要写的是C++11之后的代码,所有指针当然还是要习惯使用智能指针了,不要再自己delete了,以免内存泄露。常用的智能指针有unique_ptr, shared_ptr, 以及weak_ptr。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void UseRawPointer()
{
    // Using a raw pointer -- not recommended.
    Song* pSong = new Song(L"Nothing on You", L"Bruno Mars"); 

    // Use pSong...

    // Don't forget to delete!
    delete pSong;   
}


void UseSmartPointer()
{
    // Declare a smart pointer on stack and pass it the raw pointer.
    unique_ptr<Song> song2(new Song(L"Nothing on You", L"Bruno Mars"));

    // Use song2...
    wstring s = song2->duration_;
    //...

} // song2 is deleted automatically here.

unique_ptr

Allows exactly one owner of the underlying pointer. Use as the default choice for POCO unless you know for certain that you require a shared_ptr. Can be moved to a new owner, but not copied or shared. Replaces auto_ptr, which is deprecated. Compare to boost::scoped_ptr. unique_ptr is small and efficient; the size is one pointer and it supports rvalue references for fast insertion and retrieval from C++ Standard Library collections. Header file: <memory>.

How to: Create and use unique_ptr instances

unique顾名思义,该指针只能有一个owner,所以unique_ptr不允许拷贝操作。unique_ptr指针指向的对象,允许用户进行move操作并移交ownership给新的unique_ptr, 而旧的unique_ptr则被重置,指向null。

shared_ptr

Reference-counted smart pointer. Use when you want to assign one raw pointer to multiple owners, for example, when you return a copy of a pointer from a container but want to keep the original. The raw pointer is not deleted until all shared_ptr owners have gone out of scope or have otherwise given up ownership. The size is two pointers; one for the object and one for the shared control block that contains the reference count. Header file: <memory>.
shared顾名思义,也是只一个对象指针允许有多个owner, shared_ptr会有一个专门的指针控制reference count。所以当shared_ptr指向的对象reference count=0的时候才会delete原对象。

How to: Create and Use shared_ptr instances

weak_ptr

Special-case smart pointer for use in conjunction with shared_ptr. A weak_ptr provides access to an object that is owned by one or more shared_ptr instances, but does not participate in reference counting. Use when you want to observe an object, but do not require it to remain alive. Required in some cases to break circular references between shared_ptr instances. Header file: <memory>.

How to: Create and use weak_ptr instances

weak_ptr是对shared_ptr的一个补充,其目的也是想能够访问shared_ptr共享的对象,但是不占用其referene count。

Referennce

https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=msvc-160 https://www.geeksforgeeks.org/smart-pointers-cpp/



-->