Skip to content

Instantly share code, notes, and snippets.

@xymopen
Created October 17, 2017 14:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xymopen/352cbb55ddc2a767ed7c5999cfed4d31 to your computer and use it in GitHub Desktop.
Save xymopen/352cbb55ddc2a767ed7c5999cfed4d31 to your computer and use it in GitHub Desktop.
C++ equivalences of the famous offset_of and container_of(owner_of) macro from Linux kernel
template< class T, class M >
static inline constexpr ptrdiff_t offset_of( const M T::*member ) {
return reinterpret_cast< ptrdiff_t >( &( reinterpret_cast< T* >( 0 )->*member ) );
}
template< class T, class M >
static inline constexpr T* owner_of( M *ptr, const M T::*member ) {
return reinterpret_cast< T* >( reinterpret_cast< intptr_t >( ptr ) - offset_of( member ) );
}
@SayanNS
Copy link

SayanNS commented Jul 26, 2021

Hi, could you please write an example of how to use these templates?

@xymopen
Copy link
Author

xymopen commented Aug 1, 2021

@SayanNS Hi, I've upload the sketch using the snippet. You can see how it was used in the kenerl-list class. In general, this snippet is used to implement intrusive containers, where dynamic memory allocation is strongly discouraged, such as an OS kernel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment