I borrowed this from another question about fragmentation, but I’m not bothered by that. I’m more worried that I don’t understand the function at all. in terms of types and data lifetimes 🙁
The same data is represented by a std::vector, (a dynamic aray type with internal metadata), a pointer to the string data therein, (return parameter), and the declared return type, which is a std:string.
QUESTIONS:
How does the data get safely out of the function when the std::vector is going to be destroyed? Is it implicitly copied? Is the dynamic array of char in the vector ‘detached’ from the vector and returned as a std::string type so that no bulk copy is required? Sometimes, I think that C++ and the std library is trying to get me…
I’ve been using C++ for some while but stuff like this does my ‘ed in.
std::string TestFragmentation()
{
std::vector<char> buffer(500);
SomeCApiFunction( &buffer[0], buffer.size() ); // Sets buffer to null-terminated string data
return &buffer[0];
}
The data stored by a
std::vectoris guaranteed to be contiguous, so&buffer[0]gets you a raw pointer to the beginning of that data.1And
std::stringhas a constructor which takes aconst char *, which copies the data. That is being implicitly called in the return statement (the compiler is allowed to call at most one implicit conversion operation to avoid compile-time errors).In both cases (the
vectorand thestring), the memory for the corresponding backing buffer is managed by the container class, so there is no possibility of a memory leak or similar (so long as your raw C function creates a valid null-terminated C-style string and doesn’t trample beyond the buffer bounds).1. Note, however, that there are no guarantees that it will stay in one place. As soon as you grow or shrink the vector, it’s likely that it will be copied elsewhere in memory, invalidating all raw pointers that were pointing at it. And if the
vectoritself is destructed, then of course the backing data is no longer valid.