shared_ptr

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Foo
{
public:
	Foo(int number)
		: number(number)
	{
		cout << "ctor(" << number << ")"<< endl;
	}
	~Foo()
	{
		cout << "dtor(" << number << ")"<< endl;
	}

	int number;
};

void main()
{
	vector<shared_ptr<Foo>> list;

	for (int i = 0; i < 10; i++)
	{
		list.push_back( make_shared<Foo>(i) );
	}


	for (auto itr : list )
	{
		cout << itr->number << endl;
	}

	shared_ptr<Foo> temp( list[0] );

	list.clear();

	cout<< "list cleared"<< endl;

}

/*
result:
ctor(0)
ctor(1)
ctor(2)
ctor(3)
ctor(4)
ctor(5)
ctor(6)
ctor(7)
ctor(8)
ctor(9)
0
1
2
3
4
5
6
7
8
9
dtor(1)
dtor(2)
dtor(3)
dtor(4)
dtor(5)
dtor(6)
dtor(7)
dtor(8)
dtor(9)
list cleared
dtor(0)
*/

range for가 지원되니까 정말 좋다.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.