-2

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?

parth
  • 272
  • 1
  • 9
  • 20
  • One is a pointer (I guess) to a node allocated on the heap, the other is a node on the stack (presumably). – Some programmer dude Feb 10 '13 at 08:32
  • Are the types of n the same in these two cases? – Paul Hankin Feb 10 '13 at 08:32
  • 5
    The difference between these two is similar to the difference between political parties: they seem to do radically different things, however, in fact, they just use up all your resources. –  Feb 10 '13 at 08:33

3 Answers3

3

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2
  1. node* n = new node; is allocated on heap
  2. node n; is allocated on stack

In 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.

Edward A
  • 2,291
  • 2
  • 18
  • 31
  • 2
    "you must use `node*`"... or [a smart pointer](http://stackoverflow.com/a/106614/78845), such as `std::auto_ptr`... – johnsyweb Feb 10 '13 at 08:36
1

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 deleted.

Also, the n in n = new node must be a pointer, created like this: node* n;

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78