I want to get the size (in bytes) of struct testB here:
struct testA
{
int x;
};
struct testB
{
std::string guid;
testA userData;
};
I can get the size like this but it’s stupid:
int testA::size()
{
return sizeof(testA);
}
int testB::size()
{
return guid.size()*sizeof(TCHAR) + userData.size();
}
Are there simpler solutions?
Ps: the problem at hand is like this:
I want to story an object to database, so when my application crashes, I can get my data back. So I used sqlite, and save all the members of the struct in seperate rows. Everything goes fine, except that I have a member who hold the binary string of a Protobuf message, which can’t be inserted into the database because it will make the SQL sentence invalid.
So I come to 2 solutions:
1 serialize the protobuf message into a json/XML text, which seems to be tedious to me
2 dump all the content into the db using sqlite3_bind_blob whose third param is the size of the blob data in bytes, so the question is : how to get the size of the struct (which is quite complicated)?
is possibly what you want, or
Without some kind of description of the problem at hand, there’s no way to come to a specific conclusion.
The most obvious use for this information would be to evaluate program memory usage. This strategy isn’t appropriate for that. Use a profiler or whatever debugging tools are available on your platform to report the number and total size of allocations while running real-world test cases. For example, Valgrind should do this.
EDIT: You want to pass the size to
sqlite_bind_blob, which takes avoid *pointer to unformatted memory and a number of bytes to read from that pointer.An interface accepting a
void *will not be aware of any data structures such as implemented by the STL. Thevoid *needs to come from a flat structure with no pointers and a very stable binary format. The C++ terminology is “standard layout” and the simplest thing is not to use any C++ features at all.In this case, you could write something like
But really the best thing would be to put the GUID in another database column outside this blob. The database might optimize storage of GUIDs, and you’re likely to want to look up records by GUID as well.