Search code examples
c++vectorstructsizeofvolatile

C++ How to get sizeof of parent datatype?


  1. I have struct A that holds struct B.
  2. I want to have an int inside struct B to hold the size of struct A ().
  3. However, struct B has a vector of an unknown size that may differ at any time.
  4. The volatile vector will constantly change struct A's size.

How would I go about doing this without creating pointers?

struct A {
    struct B {
        std::vector<int> some_Vector;       // unknown size
        size_t A_size = ????;               // must always return the total size of A
    };

    B struct_B;
};

Solution

    1. The size of the vector itself (as given by sizeof) is constant, and will not be affected by how many elements it holds. Differentiate between its "logical size" and "physical size". After all, sizeof(std::vector<int>) must evaluate to something, and there aren't any object in the vector, there isn't a vector at all. The contents of the vector only affect the value returned by the member std::vector::size.

    2. So the size of each structure will be something constant. You just need to obtain it after both structures are fully defined. You can accomplish that with a constructor. Instead of a default initializer.

      struct A {
          struct B {
              std::vector<int> some_Vector;      
              size_t A_size;
              B();               
          };
      
          B struct_B;
      };
      
      A::B::B() : A_size{sizeof(A)}, some_Vector{} {
      }
      

    Though, to be frank, I see little reason why anyone would want to capture the sizeof a structure and hang on to it at run-time. It is, as I already said, constant.