Suppose I have a class
class Foo {
:
:
}
I have another function
void getf( Foo &f) {
:
:
std::cout<<sizeof f<<std::endl;
}
After I process the data and assign a lot of data to f (vector included in Foo members), I need the size of f object
However, as what I did above, I always get 16, which is the size of a reference here.
Did I do anything wrong? How to do that?
Thanks!
sizeof
returns the size of a type. Often time, as in the case of a Vector
, the size of the type does not necessarily include the cumulative size of everything the type may point to. For example, the type:
class Foo {
char* chars
}
... will exhibit the same sizeof results whether chars
points to a single byte or it points to a 40Kb string.
According to this IBM reference, sizeof
applied to a reference returns the size of the referenced object:
The result is the size of the referenced object.
So, I believe the problem is not that sizeof
is returning the size of the reference itself, but instead that Foo
holds pointers to other types.
Also keep in mind that sizeof
will not tell you the size of data inside a vector
(or any other container that uses the heap). Consider the following example:
struct Foo {
std::vector<int> v;
}
int main(int argc, char **argv) {
Foo foo;
std::cout << sizeof(foo) << std::endl;
foo.v.push_back(1);
std::cout << sizeof(foo) << std::endl;
}
Output:
24
24
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With