Constructing a temp object and calling a method that returns a pointer - is it safe?
My intution says it isn't, but the fact that everything is going on in the same line is a bit confusing. I wonder if the pointer is still valid when cout
uses it.
#include <iostream>
#include <string>
struct A {
A() : m_s("test"){ }
const char* c_str() { return m_s.c_str(); }
std::string m_s;
};
int main() {
std::cout << "abc " <&l开发者_开发百科t; A().c_str() << " def" << std::endl;
}
Yes, it is safe. The temporary A()
is destroyed at the end of the statement. That is after cout used the pointer returned.
The value returned by c_str() is valid as long as the std::string it was obtained from is unchanged and has not been destroyed. So your code is perfectly OK, as the temporary you create will have a lifetime equivalent to the full expression (the cout chain in this case) that it is part of.
It is safe provided content doesn't change in between the call.
The address that is returned, is indeed pointing to valid location of the char*.
精彩评论