C++临时对象销毁时间

下面这段代码会输出什么?

const char* p = string("hello temprary string").c_str();
cout << p;
下面这段代码运行之后会怎样?

#include <vector>

class Foo
{
public:
	Foo()
	{
		_p = new char[32];
	}
	~Foo()
	{
		delete _p;
	}
private:
	char* _p;
};
int main()
{
	std::vector<Foo> cont;
	cont.push_back(Foo());
	return 0;
}
第一个会输出奇怪的字符串,第二个会崩溃。

Why?这是临时对象提前销毁造成的。

临时对象会在什么情况下被创建,msdn上介绍有以下几种情况:

  • To initialize a const reference with an initializer of a type different from that of the underlying type of the reference being initialized.

  • To store the return value of a function that returns a user-defined type. These temporaries are created only if your program does not copy the return value to an object. For example:

    UDT Func1();    //  Declare a function that returns a user-defined
                    //   type.
    
    ...
    
    Func1();        //  Call Func1, but discard return value.
                    //  A temporary object is created to store the return
                    //   value.
    

    Because the return value is not copied to another object, a temporary object is created. A more common case where temporaries are created is during the evaluation of an expression where overloaded operator functions must be called. These overloaded operator functions return a user-defined type that often is not copied to another object.

    Consider the expression ComplexResult = Complex1 + Complex2 + Complex3. The expression Complex1 + Complex2 is evaluated, and the result is stored in a temporary object. Next, the expression temporary + Complex3 is evaluated, and the result is copied to ComplexResult(assuming the assignment operator is not overloaded).

  • To store the result of a cast to a user-defined type. When an object of a given type is explicitly converted to a user-defined type, that new object is constructed as a temporary object.

临时对象何时被销毁呢,还是看msdn的介绍:

Temporary objects have a lifetime that is defined by their point of creation and the point at which they are destroyed. Any expression that creates more than one temporary object eventually destroys them in the reverse order in which they were created. The points at which destruction occurs are shown in the following table.

Destruction Points for Temporary Objects

Reason Temporary Created

Destruction Point

Result of expression evaluation

All temporaries created as a result of expression evaluation are destroyed at the end of the expression statement (that is, at the semicolon), or at the end of the controlling expressions for forifwhiledo, and switch statements.

Initializingconstreferences

If an initializer is not an l-value of the same type as the reference being initialized, a temporary of the underlying object type is created and initialized with the initialization expression. This temporary object is destroyed immediately after the reference object to which it is bound is destroyed.

注意第一条:由于表达式的计算产生的临时对象会在表达式计算完成(遇到;号)之后被销毁。

所以:

第一个问题中,p在第一行代码之后指向了一被销毁的内存。

第二个问题中,Foo在push_back的那行代码之后被销毁,_p被delete。而vector析构的时候会析构每个元素,_p又被delete,崩溃!

编译器默认的operator=只是赋值每一个字段。要解决第二个问题,可以在operator=中对_p申请另外的内存再拷贝。

关于临时对象的析构造成的问题还可以举出很多例子。掌握了它析构的时机才能很好的避免类似错误。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
回答: 在C++中,临时对象和匿名对象是两个不同的概念。 临时对象是在表达式中创建的对象,它们在表达式结束后会被销毁临时对象通常用于函数返回值、函数参数传递和运算符重载等情况。例如,在例子1中,A(10)就是一个临时对象,它在调用myshow()函数后会被销毁。 匿名对象是没有被命名的对象,它们通常用于临时操作,不需要被引用或使用。匿名对象在创建后会立即被销毁。例如,在例子1中,A(11)和A(12)都是匿名对象,它们在被赋值给a和b后会被销毁临时对象和匿名对象的生命周期取决于它们的使用方式和上下文。在例子3中,Cat cc = Cat()创建了一个匿名对象,并将其赋值给cc对象,这个匿名对象的生命周期就变成了cc对象的生命周期。 总结起来,临时对象是在表达式中创建的对象,而匿名对象是没有被命名的对象。它们的生命周期取决于它们的使用方式和上下文。 #### 引用[.reference_title] - *1* *3* [C++匿名对象](https://blog.csdn.net/u014583317/article/details/108705360)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C++基础——匿名对象介绍、拷贝对象时的一些编译器优化](https://blog.csdn.net/weixin_69283129/article/details/127823416)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值