Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string and placement new

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?

like image 616
user181218 Avatar asked Dec 15 '22 22:12

user181218


1 Answers

You're misunderstanding the (typical) internal implementation of std::string. Usually it's implemented something like this:

class string {
protected:
    char *buffer;
    size_t capacity;
    size_t length;

public:
    // normal interface methods
};

The key point is that there are two distinct blocks of memory: one for the string object itself, containing the members shown above, and one for the content of the string. When you do your placement new, it's only the string object that is placed into the provided memory, not the memory for buffer, where the content of the string is stored. That is allocated separately, automatically, by the string class as needed.

like image 147
Eric Melski Avatar answered Dec 17 '22 13:12

Eric Melski