How to use shared_ptr in C++

7 Answers

0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;
	
	cout << *p1 << endl;
	cout << p1 << endl;

	std::shared_ptr<int> p2(p1);

	cout << *p2 << endl;
	cout << p2 << endl;


	return 0;
}


/*
run:

13
006B6044
13
006B6044

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;

	std::shared_ptr<int> p2(p1);

	cout << p2.use_count() << endl;
	cout << p1.use_count() << endl;

	return 0;
}


/*
run:

2
2

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;

	std::shared_ptr<int> p2(p1);

	if (p1 == p2)
	{
		cout << "p1 == p2" << endl;
	}

	return 0;
}


/*
run:

p1 == p2

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;

	std::shared_ptr<int> p2(p1);

	p1.reset();

	cout << p1 << endl;

	cout << *p2 << endl;
	cout << p2 << endl;

	cout << p1.use_count() << endl;
	cout << p2.use_count() << endl;

	return 0;
}


/*
run:

00000000
13
00406044
0
1

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;

	std::shared_ptr<int> p2(p1);

	p1.reset(new int(489));

	cout << *p1 << endl;
	cout << p1 << endl;

	cout << *p2 << endl;
	cout << p2 << endl;

	cout << p1.use_count() << endl;
	cout << p2.use_count() << endl;

	return 0;
}


/*
run:

489
00675C48
13
00676044
1
1

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();

	*p1 = 13;

	std::shared_ptr<int> p2(p1);

	p1 = nullptr;

	cout << p1 << endl;

	cout << *p2 << endl;
	cout << p2 << endl;

	cout << p1.use_count() << endl;
	cout << p2.use_count() << endl;

	return 0;
}


/*
run:

00000000
13
00396044
0
1

*/

 



answered Feb 1, 2018 by avibootz
0 votes
#include <iostream>
#include  <memory>

using std::cout;
using std::endl;

int main()
{
	std::shared_ptr<int> p = std::make_shared<int>();

	*p = 13;

	p = nullptr;

	if (!p)
	{
		cout << "p == NULL" << endl;
	}

	return 0;
}


/*
run:

p == NULL

*/

 



answered Feb 1, 2018 by avibootz
...