如何确定对象的运行时大小?
我们讨论的不是size of the type,而是对象的实际大小,它在执行过程中可能会发生变化,例如:
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); 在向量的情况下,它可以像这样实现:
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
}但是,对于任意类型的对象,有没有一种标准/通用的方法来做到这一点呢?ABI是否需要绕过所有实现细节?
发布于 2014-08-28 15:30:38
不,没有通用的方法可以做到这一点,因为你需要一种通用的方法来识别对象中的指针并找到它们的引用的大小。如果你发现了一个空的*怎么办?如果你找到一个指向数组的指针怎么办?在某些情况下,你甚至无法计算这些东西的大小!
https://stackoverflow.com/questions/25543077
复制相似问题