1

How can one determine the runtime size of an object ?

We're not talking about the size of the type but the actual size of an object that can vary during the execution, eg :

vector<int> v;
auto a = MagicSizeF(v); // magic size function
v.push_back(2);
v.push_back(2);
// this should hold - ok there's small consainer optimizations and initial 
// vector capacity and implementation details, but you get what I mean
assert(MagicSizeF(v) > a); 

In the vector case it could be implemented like this :

template<typename T>
auto MagicSizeF(vector<T> const& v) { 
    return v.size()*sizeof(T); // or v.capacity() to be strict
    // other implementation details memory consumers could be added
}

but is there a Standard / generic way to do this for objects of arbitrary type ? Is an ABI needed to bypass all the implementation details ?

Community
  • 1
  • 1
Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153
  • 2
    Unrelated to your actual question, but small buffer optimization is not possible with `std::vector` because `swap()` is not allowed to invalidate iterators. – Praetorian Aug 28 '14 at 07:55

1 Answers1

5

No, there is no generic way to do it, because you would need a generic way to identify pointers within objects and find the size of their referents. What if you find a void*? What if you find a pointer to an array? You can't even calculate the size of those things in some cases!

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 3
    In addition, you can't say wether the object pointed to actually belongs to the object it points to. If you follow every pointer you encounter and sum up the elements you find, you'd get infinite size whenever you have two objects pointing at each other. If you factor in some means to avoid double-counting the objects, the "MagicSize" of a leaf would still be the size of the whole *forest* which is usually not what you need and makes the function pretty useless. – Arne Mertz Aug 28 '14 at 07:56
  • @ArneMertz: quite right. The issues very much resemble those discussed at length by the inimitable Raymond Chen, here: http://blogs.msdn.com/b/oldnewthing/archive/2004/12/28/336219.aspx – John Zwinck Aug 28 '14 at 08:12