Reputation: 7448
If I have the following two functions
std::string foo1()
{
std::string temp;
...
return temp;
}
and
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}
and a function that takes a const char* as input;
void bar(const char* input) { ... }
Which one is safer to do:
bar(foo1().c_str());
or
bar(foo2());
If all I want to do is pass a string as an input to bar and then not care about the return value of either foo
function will it actually matter?
Upvotes: 2
Views: 1069
Reputation: 45410
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}
foo2()
is unsafe, you are returning a const char*
to a local variable which will point to garbage when the function returns.
Just use foo1
which is a safe and idiomatic way in C++ to return an object. NRVO may kick-in
which will elide the copy of temp when foo1
returns.
std::string foo1()
{
std::string temp;
...
return temp;
}
Upvotes: 8
Reputation: 1310
The foo2
version is unsafe because the pointer returned by c_str()
is invalidated as the std::string
temp
is destroyed when returning from foo2
. foo1
is safer as it returns a copy of the std::string
temp
.
Upvotes: 1
Reputation: 22890
The character array of c_str is valid as long as the original string object is not destroyed. This has been asked before.. At the end of your function, temp
is destroyed, which means foo2()
return an invalid pointer.
Upvotes: 2
Reputation: 305
bar(foo2()); is just plain wrong... because when foo2 returns, the temp std::string is destroyed and the pointer returned by c_str() now points to an invalid location.
Upvotes: 2
Reputation: 4932
foo2
returns a pointer to the internals of a local variable that is destroyed when going out of the function. (That's bad)
Upvotes: 0
Reputation: 258548
const char* foo2()
{
std::string temp;
...
return temp.c_str();
}
isn't safe at all, as temp
will be destroyed, so you'll be returning a dangling pointer.
Upvotes: 6