Re: static_cast vs. reinterpret_cast
Damien Kick wrote:
[snip]
I'm having a hard time, though, coming up with an example where I can
get different run-time behavior from "the same cast", i.e. casting the
same expression to the same type, with the only difference being between
static_cast and reinterpret_cast.
[...]
Damien-Kicks-Computer:~/tmp dkick$ cat duff.cc
#include <iostream>
#include <ostream>
class X {
int y_;
int z_;
public:
X(int y, int z) : y_(y), z_(z) { }
operator int() const { return y_ + z_; }
};
int main()
{
X x(13, 69);
std::cout << static_cast<int>(x) << '\n';
#if 0
// These two statements will not compile...
std::cout << reinterpret_cast<int>(x) << '\n';
std::cout << *static_cast<int*>(&x) << '\n';
#endif
std::cout << *reinterpret_cast<int*>(&x) << '\n';
}
Damien-Kicks-Computer:~/tmp dkick$ g++ duff.cc -o duff
Damien-Kicks-Computer:~/tmp dkick$ ./duff
82
13
Damien-Kicks-Computer:~/tmp dkick$
But I can only get this example to work if I use "different casts", i.e.
something about the type or the expression has to be different.
Try:
#include <iostream>
#include <cstddef>
struct A {
int i;
};
struct B {
int j;
};
struct D : public A, public B {};
std::ptrdiff_t offset_diff ( void* a, void* b ) {
return ( reinterpret_cast< std::size_t >( a ) -
reinterpret_cast< std::size_t >( b ) );
}
int main ( void ) {
D d;
A* a_ptr = &d;
B* b_ptr = &d;
D* d_ptr = &d;
std::cout
<< offset_diff ( static_cast<D*>( a_ptr ),
static_cast<D*>( d_ptr ) ) << '\n'
<< offset_diff ( static_cast<D*>( b_ptr ),
static_cast<D*>( d_ptr ) ) << '\n'
<< offset_diff ( reinterpret_cast<D*>( a_ptr ),
reinterpret_cast<D*>( d_ptr ) ) << '\n'
<< offset_diff ( reinterpret_cast<D*>( b_ptr ),
reinterpret_cast<D*>( d_ptr ) ) << '\n';
}
On my machine:
0
0
0
4
Best
Kai-Uwe Bux
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]