I found this example of using placement new in C++, and it doesn't make sense to me. It is my view that this code is exception-prone, since more memory than what was allocated may be used.
char *buf = new char[sizeof(string)];
string *p = new (buf) string("hi");
If "string" is the C++ STD::string class,then buf will get an allocation the size of an empty string object (which with my compiler gives 28 bytes), and then the way I see it if you initialize your string with more chars you might exceed the memory allocated. For example:
string *p = new (buf) string("hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
On my VS this seems to be working nevertheless, and I'm not sure if this is because the exception is somehow waived or I simply don't understand how string works.
Can someone help clarify?
The size returned by sizeof
is the number of bytes required to store the members of the class, with some implementation-defined padding. That memory must be allocated before the constructor of std::string
can be called.
However, when the constructor runs, it may allocate a larger amount of memory, which indeed it must in order to store large strings. That amount of memory is not part of the sizeof
size, and you don't need to allocate it yourself.