by intermittence reference I mean the following
shared_ptr<int> a = new int(100);
int* i = a;
shared_ptr<int> b = i;
would the reference count of b be two?
also if it is aware, would still be valid in the following code?
//
shared_ptr<int> a = new int(100);
{// workspace
int* i = a;
shared_ptr<int> b = i;
}// end of workspace
If no to above question, how could I achieve it? I would to make my memory allocation safe by using smart pointer. I have a data structure tree that would create new tree nodes (pointers to allocated memory) that is either inserted into tree or passed out. If it is within the tree, no problem, I can control the life cycle. If it is passed out, then I have no control.
CodePudding user response:
The version you wrote in your example will not compile. But to answer the spirit of what I think your question is here is an example
#include <memory>
int main() {
std::shared_ptr<int> a = std::make_shared<int>(100);
int* i = a.get();
std::shared_ptr<int> b(i);
}
This does not have a
and b
related as far as reference counting. Instead they both (mistakenly) take ownership of the same underlying pointer, pointed at by i
and will result in a double free or corruption
when a
falls out of scope since they both try to delete it.
The correct way for both shared_ptr
to reference the same underlying pointer and have correct reference counting behavior is simply
#include <memory>
int main() {
std::shared_ptr<int> a = std::make_shared<int>(100);
std::shared_ptr<int> b = a;
}