简体   繁体   中英

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. 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.

No difference. In both cases a new string object is created (1 - implicitly, 2 - explicitly).


Both examples do the following: 1. Push pointer of the empty string to the stack (or write it to the register). 2. Create new instance of string class (with specified string). 3. Write pointer of newly created instance to EAX (as the result)


My apologies, this is C++ question whereas I thought about C#:)

That means the instance of string class will be duplicated (not returned by pointer). 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.

The answer : no difference, only one temporary object (provided no compiler optimization applied).

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). The only difference is that 1st example creates an instance of string class implicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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