Reputation: 10324
is there any method to know the dynamic size of an object?
I mean, i have some objects that can increase their size during the execution and i would like to monitorate it.
I need some method like sizeof() but that it can be used with dynamic object and that it returns the actual memory usage for that object..
Thank you in advance,
Upvotes: 1
Views: 1787
Reputation: 8587
A vector
is a dynamic container for any data type. Usage: std::vector <data_type> my_variable;
For instance : vector <int> my_int_Vec;
to declare a vector of int.
Use vector::size
to know the number of elements that the vector is holding.
Use vector::capacity
to know the memory that has been allocated by the computer for your vector. The capacity may be more than the size, to accommodate for vector growth.
#include <vector>
#include <iostream>
using namespace std;
int main( )
{
vector <int> my_int_Vec;
vector <int>::size_type Size_my_int_Vec, Capacity_my_int_Vec;
my_int_Vec.push_back( 1 );
Size_my_int_Vec = my_int_Vec.size( );
Capacity_my_int_Vec = my_int_Vec.capacity( );
cout << "Vector contains " << Size_my_int_Vec << " elements." << endl;
cout << "Vector size is " << Size_my_int_Vec * sizeof(int) << " bytes.\n" << endl;
cout << "Vector capacity is " << Capacity_my_int_Vec * sizeof(int) << " bytes.\n" << endl;
return 0;
}
Upvotes: 1
Reputation: 36896
Just as objects control their own logic for the "increasing their size" concept, they also must control their own logic for "returning the dynamic size". The C++ language itself does not understand what it means to "increase object size" in the way you are talking about.
The obvious example has already been posted: std::vector
provides the .size()
method. It is not provided as part of the C++ syntax; it's a runtime function.
Upvotes: 1
Reputation: 206546
There is no such in-built feature provided by the language.
The constructs that langauge provides doesn't need you to know the size as such and the user of the language is abstracted from it.
In case You still need it You the user will have to keep track of it yourself.
Upvotes: 4