Is the following safe as is, without an explicit cast or call to std::string constructor? If not safe, why not?
std:string myfunc()
{
char buf[128] = "";
// put something into buf or not base on logic.
return buf;
}
Yes. That is perfectly fine. The caller will get a copy of the local buffer, because std::string
would make a deep-copy out of this local buffer!
EDIT: I'm assuming the buf
is null-terminated string!
Yes that is fine, remember in C++, what will happen is an implicit constructor will be called to create the return object, and a string can be constructed with a character array. In C++ you have to explicitly return by reference if you don't want a copy created.
Actually, it is safe. But that's just because you are initializing the char array
like that, which is extremely important. Consider the following code:
#include <string.h>
#include <iostream>
#include <string>
std::string alloc_string(bool fill)
{
char buf[128] = ""; // Proper declaration/initialization of the array.
if (fill)
{
strcpy(buf, "qwerty");
}
return buf;
}
int main()
{
std::string empty_str = alloc_string(false);
std::cout << "empty_str size is: " << empty_str.size() << std::endl;
std::string str = alloc_string(true);
std::cout << "str size is: " << str.size() << std::endl;
std::cout << "str: " << str << std::endl;
}
Outputs:
empty_str size is: 0
str size is: 6
str: qwerty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With