Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

visual c++ - Most portable and reliable way to get the address of variable in C++

Using & to get an address of a variable can be problematic if the variable type has overloaded operator&(). For example, _com_ptr_ has operator&() overloaded with a side effect of modifying the object.

Now I have a complicated set of templates with functions like this:

template<class T>
void process( const T* object )
{
    //whatever
}    

template<class T>
void tryProcess( T& object )
{
    process( &object )
}

In tryProcess() I need to get a T* pointer holding the address of the actual object of type T.

The above implementation of tryProcess() will only work allright if class T doesn't have operator&() overloaded. So if I call tryProcess<_com_ptr_<Interface>>() I can get unexpected results - the overloaded operator&() is triggered.

In another question the following workaround is suggested:

template<class T>
T* getAddress( T& object )
{
   return reinterpret_cast<T*>( &reinterpret_cast<char&>( object ) );
}

With such a function I can implement tryProcess() as follows:

template<class T>
void tryProcess( T& object )
{
    process( getAddress( object ) )
}

and will always get the same behavior independent of whether class T has operator&() overloaded. This introduces zero overhead with optimizations on on Visual C++ 7 - the compiler gets what to do and just gets the object address.

How portable and standard-compilant is this solution to the problem? How could it be improved?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Boost addressof is implemented with that reinterpret_cast trick so I'd say it's probably portable and standard-conforming.

Here you can see the code in question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...