I have checkd gcc and clang and both does not generate any warnings. I suppose that lifetime of temporary from foo() will be prolonged untill the end of full expression which is where semicolon in bar function call is located.
#include <iostream>
#include <string>
struct A
{
std::string foo() const{ return "aaa"; }
};
void bar(const char* c) {
std::cout << c;
}
int main()
{
A a;
bar(a.foo().c_str()); // Is this safe?
bar(a.foo().substr().c_str()); // or this
}
The temporary returned by foo()
(and substr()
) will continue to exist until the end of the bar
call (after the chain of method calls), this is safe.
int main()
{
A a;
bar(a.foo().c_str());
//temporary is destroyed here
bar(a.foo().substr().c_str());
// and here
}
Classical undefined behaviour case :
int main()
{
A a;
const char* charPtr = a.foo().c_str();
printf("%s", charPtr);
}
Temporary std::string
is created, a pointer to it's buffer is returned by c_str()
and the temporary goes out of scope and is destroyed. charPtr
now is a pointer pointing to an invalid location ( a dead std::string
).
bar(a.foo().c_str());
bar(a.foo().substr().c_str());
Short answer - Yes, both are safe.
What you're looking at is an rvalue.
An rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object.
Read more: What are rvalues, lvalues, xvalues, glvalues, and prvalues?
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