I am playing around with boost scoped pointers and I don't understand this behaviour:
#include <iostream>
#include <boost/scoped_ptr.hpp>
int main()
{
boost::scoped_ptr<int> p{new int{1}};
std::cout << &p << '\n';
p.reset(new int {2});
std::cout << &p << '\n';
return 0;
}
I get the following output:
0x7fff5fbff650
0x7fff5fbff650
Shouldn't the reset function change the address pointed by p? this is the case if use a scoped array instead of a scoped pointer and print the address pointed by the first element in the code above.
When you do
std::cout << &p << '\n';
you are getting the address of p
, not what p
points to. To get that you need
std::cout << static_cast<void*>(p.get()) << '\n';
The static_cast<void*>()
is not really needed in this example as printing a pointer, other than a char*
/const char*
will give you its address but I added it to just be safe.
You're taking the address of the scoped_ptr
called p
. There's only one of them!
If you'd printed &*p
or p.get()
instead (though prefer (void*)p.get()
for sanity) then you'd be printing the address of the thing it currently points to.
This address will always change, because you create the second object (using new
) slightly before the first one is destroyed, and objects cannot share addresses.
If you'd done a .reset()
first, though, then you may or may not see this address changing, depending on what the innards of new
did; objects don't have to have addresses unique to the lifetime of your program, as long as they don't share the address of another object that still exists! However, even then, in practice, to be honest, I'd be surprised if the second dynamically-allocated int
wound up at the same address as the first.
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