Suppose I have the following class template:
template<typename T>
struct Wrapper {
T* t_;
static void check() {
static_assert(sizeof(Wrapper<T> == sizeof(T*), "Illegal assumption");
}
};
I looked in the C99 standard an in the C++03 standard and cannot find a guarantee for my assumption expressed in the static_assert
. I tried it on Visual C++ 2008 and 2010 (32bit) and gcc on linux (64bit) using several compiler options and found my assumption confirmed.
My question are:
I guess a compiler might add some padding to the struct e.g. for debugging purposes. But is there a compiler that actually does that?
Edit: So as you asked here is what I want to achieve:
I have the member function with the following signature:
Someclass* OtherClass::fn();
I want to change the signature like this:
Wrapper<Someclass> OtherClass::fn();
This wrapper acts like some smart-pointer, i.e. it cares for the pointer's lifetime, thus it releases it when it goes out of scope. As the function is called across a dll boundary I want to make sure that the returned value (which is now a concrete type, not just a dumb pointer) is in all circumstances (i.e. compiler settings, etc) of the same size as the pointer would be. The plan/hope is to support all combination of debug/release application/dll builds.
As you might ask: no, I can not use boost::shared_ptr<>, std::shared_ptr<>, std::unique_ptr<> and the like, as we don't want to expose boost to the dll user and we don't support C++11 yet.
If you want to assume it and you have a compile-time check, then go ahead. Presumably you get some benefit out of doing this.
You aren't guaranteed anything about padding, but typically padding is used to get alignment so that arrays of the type have every member of the array (and every member of the struct) aligned properly. A native pointer is usually already the right size to be aligned, so padding isn't needed, but you aren't guaranteed that.
This isn't something you can just check with gcc -- it depends on the target architecture, not only the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With