4

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.

Jacopo
  • 43
  • 3

3 Answers3

7

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
5

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

You are printing address of object p with is a boost::scoped_ptr. You should use p.get() to get address of handle object;