Re: strict aliasing: how to swap pointers

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Rupert Wood wrote:
I don't know how to fight aliasing rules but as another approach you could template the function instead, i.e.

template<typename T> T* exchange(T** ptr, T* next);

exchange<int>(&a, &v2);

since you're using C++ here.

I initially dismissed this solution since the implementation of exchange is either a typical swap using a temporary, a compare-and-swap sequence or a mutex, depending on various compilation options. I wanted to avoid including the implementation in the header to avoid a bunch of #ifdefs. However, your email made me try to avoid the warning with a template wrapper:


template <typename T>
T* exchange_template(T** ptr, T* next) {
    return reinterpret_cast<T*>(
            exchange(reinterpret_cast<void**>(ptr), next));
}

...

exchange_template(&a, &v2);


I don't understand why, but this compiles without warnings. It also avoids needing to look up the aliasing rules, and places the dangerous cast in a single location, so this seems like a better solution.

I would still like to know if my original solution is "correct" or not, since it would be needed for C.

Evan Jones

--
Evan Jones
http://evanjones.ca/

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux