C++ sizeof wrapper class

前端 未结 3 2019
梦如初夏
梦如初夏 2021-01-17 23:23

Suppose I have a class A that does not inherit from anything, has no virtual methods, and has exactly one variable of type T. Does C++ guarantee sizeof(A) == sizeof(T)

相关标签:
3条回答
  • 2021-01-18 00:09

    I don't think it explicitly guarantees it, but I don't think it would ever be different.

    0 讨论(0)
  • 2021-01-18 00:20

    No, it might be more than sizeof(T) due to padding.

    0 讨论(0)
  • 2021-01-18 00:27

    I think C++ should guarantee sizeof(A) == sizeof(T).

    Consider bellow situation, C++ should make it works just like in C:

    A a[10];
    T t[10];
    
    A * ap = (A *) t;
    T * tp = (T *) a;
    
    memcpy(ap, tp, sizeof(*ap));
    
    0 讨论(0)
提交回复
热议问题