about shared_ptr

Mar 1, 2021 at 12:59pm
first time to use shared_ptr and wrote the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
 #include <iostream>
#include <memory>
using namespace std;
​
int main()
{
int i=19;
    int *pt=&i;
    std::shared_ptr<int> p1(pt);
    cout << *p1 << endl;
 
    return 0;
}

it output "19" and exited with error staues 134.
it seems that i initialized p1 incorretly.why?
Mar 1, 2021 at 1:23pm
Shared_ptr is for use with dynamically allocated memory - not pointers to existing variables. Also, you would usually use make_shared:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <memory>

int main()
{
	auto p1 {std::make_shared<int>(19)};

	std::cout << *p1 << '\n';
}

Mar 1, 2021 at 4:56pm
The purpose of shared_ptr and unique_ptr is to make sure that delete is called at correct moment. Alas, they trust that you give them address of dynamically allocated object.

Therefore, your program does essentially:
1
2
3
int i = 19; // not a dynamically allocated object
// something
delete &i; // error 

Mar 6, 2021 at 5:41am
Adding to what Seeplus and Keskiverto have already provided, here is how your code would need to look to work with the std::shared_ptr;
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <memory>
using namespace std;

int main()
{
    int* i = new int(19);
    int* pt = i;
    std::shared_ptr<int> p1(pt);
    cout << *p1 << endl;

    return 0;
}


shared_ptrand unique_ptr are for use in dynamically allocated memory pointers or memory allocated on the heap rather than the stack.
Your code allocated i to the stack and then you tried to access it with dynamic memory techniques. The use of the new keyword with the int creation returned a pointer reference to i dynamically created on the heap at which point the std::shared_ptr could work. Here's a link to the documentatin on the new keyword
https://en.cppreference.com/w/cpp/language/new

I'm still learning too and what I'm learning is avoid these kinds of dynamic memory allocations if you can. The Standard Library has some helpful tools to help with that. Otherwise you're going to have to write custom copy constructors, move constructor, copy assignment constructors, move assignment constructor and destructors to delete the dynamic memory allocations. C++ will build all of these things for you but the ones it builds won't always work properly in dynamic memory situations. (From what I've learned so far)


Mar 6, 2021 at 10:39am
You would usually use std:make_shared:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <memory>

int main()
{
	auto p1 {std::make_shared<int>(19)};

	std::cout << *p1 << '\n';
}

Topic archived. No new replies allowed.