While trying to explore how the compiler handles strings in C I tried the following program that compiles and runs w/o errors, but I cannot understand if it changes any memory locations or has any effect on the program flow. It doesn't seem to do anything.
#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;
}
It does generate some assembly instructions but I have no idea what they do.
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;
CodePudding user response:
It, essentially, doesn't do anything useful.
The foo function returns a copy of the string str, and you assign to this copy. It's similar to:
{
string temp;
temp = foo();
temp = "test";
// Here the temp object is destructed, and the modifications
// made to it are lost
}
Because the statement doesn't have any observable effect, the as-if rule allows the compiler to skip not only the assignment but also the call to foo itself.
Things would be very different if the foo function returned a reference to the str object:
string& foo() {
return str;
}
Because then the assignment would assign to the actual str object instead:
{
string& temp_ref = foo();
temp_ref = "test"; // Really assigns to str
}
CodePudding user response:
foo() returns a copy of str.
foo() = "test";
This line changes the copy's contents to "test" but does not store it anywhere, so effectively it does nothing.
