With normal pointers, I can declare a pointer and then set it equal to a new object, however with shared pointers I am unable to do that. Why?
#include <memory>
struct node{
int num;
node* next;
};
int main()
{
std::shared_ptr<node> new_node1 = NULL; // WORKS
new_node1 = new node; // ERROR, why?
node* new_node2 = NULL; //WORKS
new_node2 = new node; //WORKS
return 0;
}
Why can't we create a new object for a shared pointer? Is there a way to do it?
reset().new_node1.reset (new node);ornew_node1 = std::make_shared <node> ();Foo *f = new Foo(); bar(f); bar(f);. Now, what happens ifbartakes astd::shared_ptr<Foo>? (Think about the destruction of the temporary shared pointer.) You want to know for sure where and when you are constructing ashared_ptrbecause that takes over control of the lifetime of the underlying object.