If I declare a struct node in C++,after which I declare:
n = new node;
or
node n;
Are both these notations representing the same thing?
If I declare a struct node in C++,after which I declare:
n = new node;
or
node n;
Are both these notations representing the same thing?
No.
n = new Node;
is a pointer, the correct code is
Node* n = new Node;
or, with C++11 (the latest C++ standard published in 2011, ant not yet implemented by several compilers, even if latest GCC 4.7 or soon to be released 4.8 is quite near)
auto n = new Node;
Actually, using raw pointers like above is frowned upon. You should consider using smart pointers e.g.
std::shared_ptr<Node> n = new Node;
The pointed-to node will be destroyed by later calling (perhaps indirectly)
delete n;
(notice that smart pointers do that "magically" for you)
But
Node n;
declare a variable of type Node
. That Node
data is destroyed at the end of current scope (i.e. at the closing }
containing brace).
Read also about RAII.
node* n = new node;
is allocated on heapnode n;
is allocated on stackIn case 1. when you allocate on heap using the new
keyword you must use node*
because you're saving a pointer to the object not the object itself. Using heap allocation is especially useful when you are going to want to use the object outside the current scope, although you have to always remember to call delete n;
on every object allocated with the new
keyword (unless you're using std::shared_ptr
or anything along those lines).
node* make_node()
{
node* n = new node;
n->do_something();
return n;
} // node n does not go out of scope here, but you'll have to call delete on it when you're done
In case 2. the object is being allocated on stack, while you don't have to call delete
here, this one is going to go out of scope at the end of the current block:
void function()
{
node n;
n.do_something();
} // node n goes out of scope here.
Additional information about std::shared_ptr and other <memory>
goodies.
Although they represent the same thing, n
in the second case is created on the stack, where as the n
in n = new node;
is created on the heap storage, which must be manually delete
d.
Also, the n
in n = new node
must be a pointer, created like this: node* n;