Size of structure containing 1 pointer

Suppose I have the following template 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 in the C ++ 03 standard and cannot find a guarantee for my assumption expressed in static_assert. I tried this on Visual C ++ 2008 and 2010 (32 bit) and gcc on Linux (64 bit) using several compiler options, and found that my assumption was confirmed.

My question is:

  • Is my assumption reasonable for Visual C ++ 2008/2010/11 (windows)?
  • For gcc 4. * (linux)?
  • For any combination of compiler flags
  • Do you know any compiler / platform where this assumption fails?

I assume that the compiler may add some addition to the structure, for example. for debugging purposes. But is there a compiler that actually does this?

:. , , :
- :

Someclass* OtherClass::fn();

:

Wrapper<Someclass> OtherClass::fn();

, .. , , . dll, , ( , ) ( ..) , . / // dll.
: , boost:: shared_ptr < > , std:: shared_ptr < > , std:: unique_ptr < > , dll, ++ 11.

+5
3

, , . , .

, , ( ) . , , , , .

, gcc - , .

+3

, § 9.2 [class.mem]:

17/ ( 9) , ( ) (3.9).

, struct ( , , ).

20/ , reinterpret_cast, ( , , ) . [. , , , , . -end note]

, .


20/. , :

void check(T* t) {
    Wrapper<T>* w = reinterpret_cast<Wrapper<T>*>(t);
    assert(w->t_ == t);
}
+1

, .

T T, , . , , , , , .

, , C ++ , . , ++ layout, ++ C, - / .

Bottom line: if you have a pointer to the first element, you can safely convert to a pointer to a struct (or vice versa). You yourself, if you do something like creating an array of one and indexing into it, as if it were an array of the other, the chances of it working are pretty good, but I'm sure the standard doesn't guarantee it.

+1
source

All Articles