C++ 函数调用中临时对象的作用域
在下面的代码中,将在返回其内部缓冲区后创建并销毁临时字符串对象。因此p指向一个无效的内存位置C++ 函数调用中临时对象的作用域,c++,C++,在下面的代码中,将在返回其内部缓冲区后创建并销毁临时字符串对象。因此p指向一个无效的内存位置 int main() { const char* p = std::string("testing").c_str(); //p points to an invalid memory location } 在下面的代码中,将创建临时字符串对象。何时删除临时字符串对象?在执行func之后还是之前?我可以在func方法中安全地使用p指针吗 p在语句funcstd::stringtesti
int main()
{
const char* p = std::string("testing").c_str();
//p points to an invalid memory location
}
在下面的代码中,将创建临时字符串对象。何时删除临时字符串对象?在执行func之后还是之前?我可以在func方法中安全地使用p指针吗
p在语句funcstd::stringtesting.c_str;之后才有效;。这意味着在func返回之前,匿名临时字符串不会从堆栈中弹出
所以你的代码是完全安全的
void func(const char* p)
{
//p is valid or invalid ????
}
int main()
{
func(std::string("testing").c_str());
}