Does std::swap of smart pointers guarantee the references (address in memory) to be unchanged?
The std documentation states that one (of several) qualifying traits for letting class T
be swap-able, is that,
T must be assignable and T must be copy and/or move constructible
If swaping was conducted by the use of copy construction, I would suspect that the memory addresses might change. However, I also suspect that swapping by copy construction is not relevant when swapping specifically (smart) pointers.
The below code compiles (GCC) and runs smoothly without changing the address upon swapping, but do I have a guarantee for this to be so?
Note: Example is using std::auto_ptr
because it was pointed out in comments that std code is preferable over boost. I work on old C++ and do not have std::unique_ptr
available (which nevertheless have its copy constructor deleted). Original post applied boost::scoped_ptr
.
#include <boost/scoped_ptr>
#include <iostream>
class Awesome
{
public:
Awesome(int a=0) : Value(a) {}
Awesome(const Awesome& T) : Value(T.Value) {}
int Value;
};
int main()
{
std::auto_ptr<Awesome> a_ptr(new Awesome(2));
Awesome& a_ref = *a_ptr.get();
std::cout << "a_ptr's addr : " << a_ptr.get() << std::endl;
std::cout << "a_ref's addr : " << &a_ref << std::endl;
std::auto_ptr<Awesome> b_ptr;
std::swap(b_ptr, a_ptr); // <<------------------ Does this (possibly) break 'a_ref' ?
std::cout << "b_ptr's addr : "<< b_ptr.get() << std::endl;
return 0;
}
You are swapping pointers, not the objects themselves, the swap() function cannot change the address of the objects as it doesnt even know about the objects. If you are looking for guarantee then you should ask for a guarantee that destroying and moving/copying the smart pointer doesnt affect the object.
edit: This is relevant to std::swap(b_ptr, a_ptr);
, in boost there is a member function swap on the smart pointers so in theory it could do anything, but i highly doubt that it would change the address of the object when swapping pointers.