A a; a.doSomething(&a); // doSomething takes a pointer
Most of the time, we don't do self assignments or self operations intentionally. But things like this may occur. And when they occur, it may be just a waste of time since the two objects are exactly the same or just itself, for example a Vector just literally re-copies the contents of itself, which is not needed. Imagine if the Vector has 10000000 elements, that is a waste of computing power. That is why code to check for self-assignment or self-operation may be needed some time to prevent such accidents.
#include <iostream>
struct A
{
void foo() const
{ std::cout << "A::foo called on object at address " << this << "\n\n" ; }
A& bar( const A& that )
{
std::cout << "A::bar called on object at address " << this << '\n'
<< "the address of the object 'that' is " << std::addressof(that) << '\n' ;
if( this == std::addressof(that) ) std::cout << "it is the same object\n\n" ;
else std::cout << "these are two different objects\n\n" ;
A& result = *this ; // this a a pointer of type A*
// *this is an lvaule of type A
// result is a reference to the object on which bar was called
return result ; // (return *this): return reference to the object on which bar was called
}
};
int main()
{
A one ;
std::cout << "address of one is: " << std::addressof(one) << '\n'
<< "call one.foo()\n" ;
one.foo() ;
static A two ;
std::cout << "address of two is: " << std::addressof(two) << '\n'
<< "call two.foo()\n" ;
two.foo() ;
A* p_three = new A ;
std::cout << "address of object (value of p_three) is: " << p_three << '\n'
<< "call p_three->foo()\n" ;
p_three->foo() ;
delete p_three ;
std::cout << "call one.bar(two)\n" ;
one.bar(two) ;
std::cout << "call one.bar(one)\n" ;
one.bar(one) ;
}
address of one is: 0x7fff375edb38
call one.foo()
A::foo called on object at address 0x7fff375edb38
address of two is: 0x615539
call two.foo()
A::foo called on object at address 0x615539
address of object (value of p_three) is: 0x10dbc30
call p_three->foo()
A::foo called on object at address 0x10dbc30
call one.bar(two)
A::bar called on object at address 0x7fff375edb38
the address of the object 'that' is 0x615539
these are two different objects
call one.bar(one)
A::bar called on object at address 0x7fff375edb38
the address of the object 'that' is 0x7fff375edb38
it is the same object