-1

What is the difference between the following declarations?

list<int> myList;
list<int> *myList=new list<int>;

Is one declaration more suited for a particular example than the other or are they just different ways of saying the same thing? Also what is the difference between the following declarations?

list<int> *myList=new list<int>;
list<int>* myList=new list<int>;

Is one of the above declarations wrong or they are same?

niklasfi
  • 15,245
  • 7
  • 40
  • 54
fts
  • 141
  • 4
  • 14
  • possible duplicate of [When should I use the new keyword in C++?](http://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c) – juanchopanza Apr 27 '14 at 11:25
  • To your second, unrelated question: [see this](http://stackoverflow.com/a/2660643/645270). Do your research. I searched for _"asterisk space c++"_ – keyser Apr 27 '14 at 11:26

1 Answers1

1

The main difference is that the first statement is of value type, and the second of pointer type.

The first statement allocates the needed memory for a list<int> on your stack, the second statement allocates the memory needed for a pointer of type list<int>* on your stack and allocates and fills the needed memory for a list on the heap.

EDIT: To answer your second question:

list<int> *myList=new list<int>;

and

list<int>* myList=new list<int>;

are just different ways of stating the same thing. There are different arguments for and against playing the star next to the variable name or not.

niklasfi
  • 15,245
  • 7
  • 40
  • 54