foo() = "test"; 是什么意思?做?

Pan*_*nis 1 c++ string assembly

在尝试探索编译器如何处理 C++ 中的字符串时,我尝试了以下程序,该程序编译并运行时没有错误,但我无法理解它是否更改了任何内存位置或对程序流程有任何影响。它似乎没有做任何事情。

#include <iostream>
using namespace std;

string str = "this is public string\n";

string foo() {
    return str;
}

int main()
{
    foo() = "test";       //  what does this line do
    cout << str << endl;

    char c;
    cin>>c;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它确实生成了一些汇编指令,但我不知道它们是做什么的。

getString() = "test";       //  what does this line do
00007FF68B0D6F1B  lea         rcx,[rbp+0E8h]  
00007FF68B0D6F22  call        getString (07FF68B0D1640h)  
00007FF68B0D6F27  mov         qword ptr [rbp+118h],rax  
00007FF68B0D6F2E  mov         rax,qword ptr [rbp+118h]  
00007FF68B0D6F35  mov         qword ptr [rbp+120h],rax  
00007FF68B0D6F3C  lea         rdx,[string "test" (07FF68B0E1584h)]  
00007FF68B0D6F43  mov         rcx,qword ptr [rbp+120h]  
00007FF68B0D6F4A  call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::operator= (07FF68B0D1037h)  
00007FF68B0D6F4F  nop  
00007FF68B0D6F50  lea         rcx,[rbp+0E8h]  
00007FF68B0D6F57  call  std::basic_string<char,std::char_traits<char>,std::allocator<char> >::~basic_string<char,std::char_traits<char>,std::allocator<char> > (07FF68B0D1140h) 
cout << str << endl;
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 7

从本质上讲,它没有做任何有用的事情。

foo函数返回string 的副本str,并分配给该副本。它类似于:

{
    string temp;
    temp = foo();
    temp = "test";

    // Here the temp object is destructed, and the modifications
    // made to it are lost
}
Run Code Online (Sandbox Code Playgroud)

由于该语句没有任何可观察到的效果,因此as-if 规则允许编译器不仅跳过赋值,还跳过对其foo自身的调用。


foo如果函数返回对象的引用,情况会非常不同str

string& foo() {
    return str;
}
Run Code Online (Sandbox Code Playgroud)

因为这样分配就会分配给实际str对象:

{
    string& temp_ref = foo();
    temp_ref = "test";  // Really assigns to str
}
Run Code Online (Sandbox Code Playgroud)