Skip to content

Std::shared ptr

Reference example

shread_ptr을 Reference로 전달될 경우 use_count에 영향을 주지 않는다.

#include <iostream>
#include <memory>

using namespace std;

void test(shared_ptr<int> const & temp)
{
    cout << "*1. Use count: " << temp.use_count() << endl;
}

void test2(shared_ptr<int> & temp)
{
    cout << "*2. Use count: " << temp.use_count() << endl;
}

void test3(shared_ptr<int> temp)
{
    cout << "*3. Use count: " << temp.use_count() << endl;
}

int main()
{
    shared_ptr<int> temp(new int);
    cout << "1. Use count: " << temp.use_count() << endl;
    test(temp);

    cout << "2. Use count: " << temp.use_count() << endl;
    test2(temp);

    cout << "3. Use count: " << temp.use_count() << endl;
    test3(temp);

    cout << "RESET. Use count: " << temp.use_count() << endl;
    temp.reset();

    cout << "LAST. Use count: " << temp.use_count() << endl;

    return 0;
}

아래와 같이 출력된다:

1. Use count: 1
*1. Use count: 1
2. Use count: 1
*2. Use count: 1
3. Use count: 1
*3. Use count: 2
RESET. Use count: 1
LAST. Use count: 0

shared_ptr to an array

std::shared_ptr<int> sp( new int[10], std::default_delete<int[]>() );

See also

Favorite site

References


  1. DevStory_of_LunaStar_-item_19-_std_shared_ptr.pdf