![]() ![]() While C++ inherits this data structure from C, it also includes strings as a higher-level abstraction in the standard library. It has a starting point and ends with a string-termination character. In C, when we use the term string, we're referring to a variable length array of characters. C++ class which is Standard C++ string.I think your problem is your conception of sizeof, see more information here and here is some explanation on how it works. If you want to get the real size of the string, you need to call the size() method from the class which will check the memory buffer string size (which isn't the same as the memory buffer size).This pointer inside the string class, points to a memory buffer where the class will hold the real string data, this memory buffer is reallocated as needed, it can increase/decrease as you append/delete/create more string text.As the sizeof(string) is the size of the class structure, you'll get the size of the only internal pointer, that in your case is 4 bytes (because you are in a 32-bit machine, this can change from platform to platform too).It's not the size of the string or the capacity of the string, this value represents the structural size of the class string, which you can see by its implementation (and it can change from implementation to implementation) that is a simple pointer.I know a lot of people had answered your question, but here are some points: But since the 'std::string' class only holds the pointer to this potentially infite length buffer, the sizeof(std::string) always remains the same as sizeof pointer on the given architecture which on your system is 4. This can have as many elements as the system allows (C++ places no restriction on this length). Inside the 'std::string' class, there is a non static member pointer which is allocated dynamically to hold the input buffer. It does not mean that the actual buffer of characters (which is called string in common parlance) is only 4 bytes. Note that signed T, unsigned T always have the same size. It occupies 4 times the number of bytes that a 'char' on that machine takes. Having said, that assuming that 'string' is 'std::namespace', sizeof(string) = 4 means that the sizeof the 'std::string' class is 4 bytes. This is true only when a char is 8-bits, and plain char is unsigned. So it is wrong to assume that char can have only values from 0 to 255. ![]() A plain char is either signed or unsigned. The next important thing to note is that C++ has three character types: plain char, signed char and unsigned char. The sizeof applied to any other type is in multiples of sizeof(char) which is by definition 1. There are architectures where a BYTE is 32-bits, 24-bits and so on. A byte which we think is 8-bits need not be the case. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |