简体   繁体   English

c++ 临时 object 问题

[英]c++ Temporary object question

Is there a difference in the number of temp objects created between these 2 functions?这两个函数之间创建的临时对象的数量是否存在差异?

string foo1() {
    return "";
} 

string foo2() {
    string s = "";
    return s;
}

This is a homework question so please assume there is no compiler optimization.这是一个家庭作业问题,所以请假设没有编译器优化。

No- only one temporary is created.不——只创建一个临时的。 The object on the stack of the function is not a temporary, it is an lvalue. function 的堆栈上的 object 不是临时的,它是一个左值。 The string literal is also an lvalue.字符串文字也是一个左值。 Both involve exactly the same process- returning a string constructed from an lvalue.两者都涉及完全相同的过程-返回从左值构造的字符串。

Yes.是的。 Without any optimization, namely, NRVO (named return-value optimization), the second code will produce 2 temporaries while the first will produce one.如果没有任何优化,即 NRVO(命名为返回值优化),第二个代码将产生 2 个临时代码,而第一个代码将产生一个。

No difference.没有不同。 In both cases a new string object is created (1 - implicitly, 2 - explicitly).在这两种情况下,都会创建一个新字符串 object(1 - 隐式,2 - 显式)。


Both examples do the following: 1. Push pointer of the empty string to the stack (or write it to the register).两个示例都执行以下操作: 1. 将空字符串的指针压入堆栈(或将其写入寄存器)。 2. Create new instance of string class (with specified string). 2. 创建字符串 class 的新实例(使用指定的字符串)。 3. Write pointer of newly created instance to EAX (as the result) 3. 将新建实例的指针写入 EAX(结果)


My apologies, this is C++ question whereas I thought about C#:)抱歉,这是 C++ 问题,而我想到了 C# :)

That means the instance of string class will be duplicated (not returned by pointer).这意味着字符串 class 的实例将被复制(不是由指针返回)。 Anyway, both examples create only one instance of string class (1 - implicitly, 2 - explicitly), then all bytes of this instance (temporary object) will be pushed to the stack as the result.无论如何,这两个示例都只创建了一个字符串 class 的实例(1 - 隐式,2 - 显式),然后该实例(临时对象)的所有字节将作为结果推入堆栈。

The answer : no difference, only one temporary object (provided no compiler optimization applied).答案:没有区别,只有一个临时的 object(前提是没有应用编译器优化)。

NOTE: in both cases compiler allocates the same number of bytes in the stack to store the instance of string class, and the "" (empty string) is already loded to the memory (no allocation).注意:在这两种情况下,编译器都会在堆栈中分配相同数量的字节来存储字符串 class 的实例,并且“”(空字符串)已经加载到 memory(未分配)。 The only difference is that 1st example creates an instance of string class implicitly.唯一的区别是第一个示例隐式创建了字符串 class 的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM