I am learning C++ and I know the 'new' key word is used to allocate an address in memory to a pointer. And I think when using 'nullptr' initializes a pointer which points to nothing. Is that correct? Example for reference:
//using nullptr
int *x = nullptr; //this is just a pointer that points to nothing and
//will need to be initialized with an address before it
//it can be used. Correct?
//using new
int *x = new int; //this is basically giving x an address in memory. Will the
//address have some residual value stored in it or will
//it contain zero?
When would you use one over the other? Is new only used for dynamic memory allocation or are there other applications for it? Why would you initialize a pointer to nullptr if you could just declare it and then initialize it later?
Thanks for the help!
Your understanding of new int
and int *x = new int;
is not correct (or at least, the way you worded it is not correct).
new int
allocates some memory. It doesn't "allocate memory to a pointer", it just allocates memory. It supplies a pointer to that memory, which didn't exist previously.
int *x;
also allocates memory for a variable called x
. x
is a variable whose value is the address of another object. (as opposed to other types of variable, whose value may be a number or a string for example).
int *x = nullptr;
means x
holds a special value called "null pointer" that does not indicate any other object.
int *x = new int
means that x
holds the address of the piece of memory that was allocated by new int
. So there are two allocations involved in this line: x
, and the unnamed memory allocated by new
.
In the latter case you could output the address of each of these allocations separately, e.g.:
cout << &x << ',' << x << '\n';