Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of an object via reference?

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!

like image 958
skydoor Avatar asked Dec 02 '22 04:12

skydoor


2 Answers

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.

like image 105
kbrimington Avatar answered Dec 23 '22 22:12

kbrimington


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
like image 25
Justin Ardini Avatar answered Dec 23 '22 21:12

Justin Ardini