C++笔记-临时对象的生命周期

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

看下面的代码

#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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值