看下面的代码
#include <iostream>
class MyClass
{
public:
MyClass()
{
std::cout << "constructor" <<std::endl;
}
~MyClass()
{
std::cout << "deconstructor" << std::endl;
}
void print()
{
std::cout << "print" << std::endl;
}
};
MyClass getClass()
{
return MyClass();
}
int main()
{
getClass().print();
std::cout << "Hello World!\n";
}
字符串的输出顺序是:

在调用getClass()时会创建一个临时对象,但是在这个对象马上又被释放了。因此,在输出“Hello World”时,临时对象已经不存在了。
上述的代码可能没有什么隐患里面。看下面的代码
#include <iostream>
std::string getString()
{
std::string str("string");
return str;
}
int main()
{
char* pStr = (char*)getString().c_str();
if (!strcmp(pStr, "string"))
{
std::cout << "equal!\n";
}
else
{
std::cout << " no equal!\n";
}
}
在调用strcmp函数时,实际指针pStr已经是不安全的,使用pStr可能会造成一些问题。
这个隐患很难察觉。
改法:
//char* pStr = (char*)getString().c_str();
std::string str = getString();
char* pStr = (char*)str.c_str();

探讨C++中临时对象的生命周期与潜在的安全隐患,通过具体代码示例,揭示了临时对象不当处理可能导致的问题,并提供了相应的解决方案。

1178

被折叠的 条评论
为什么被折叠?



