I'm a newcomer in C++. I tested a unique pointer on my PC: I thought it would be allocated on the heap, but it shows on the stack instead. This confused me. Does a unique pointer allocate memory on the heap or stack?
#include <memory>
#include <stdio.h>
void RawPointer()
{
int *raw = new int;// create a raw pointer on the heap
printf("raw address: %p\n", raw);
*raw = 1; // assign a value
delete raw; // delete the resource again
}
void UniquePointer()
{
std::unique_ptr<int> unique(new int);// create a unique pointer on the stack
*unique = 2; // assign a value
// delete is not neccessary
printf("unique pointer address: %p\n", &unique);
}
int main(){
RawPointer();
UniquePointer();
}
and it comes in shell:
raw address: 0x555cd7435e70
unique pointer address: 0x7ffcd17f38b0
thanks bros,
What you are printing in your UniquePointer
function is the address of the std::unique_ptr
class object. This class has an internal member that is the actual address of the allocated data.
You can access this actual address using the get()
member function, as shown in the code below (which, when I tried, gave me the exact same address as for the raw pointer - though that won't always be the case):
void UniquePointer()
{
std::unique_ptr<int> unique(new int);// create a unique pointer on the stack
*unique = 2; // assign a value
// delete is not neccessary
// printf("unique pointer address: %p\n", &unique);
printf("unique pointer address: %p\n", unique.get());
}
Note: The %p
format specifier expects a void *
pointer as an argument; however, an implicit cast to a void pointer (from a pointer to another type) is well-defined behaviour - see here: void pointers: difference between C and C++.
Feel free to ask for further clarification and/or explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With