samedi 6 mars 2021

Understanding this behaviour (r-value reference)

I'm doing some tests with the following code:

#include <iostream>
#include <string>
using namespace std;

string& changeSomething(string&& s) {
    s[0] = 'a';
    return s;
}

int main() {
    string s = changeSomething("hello");
    cout << s << endl;
}

Here I pass a rvalue reference to the function, and return a reference to the object. The problem here is that I thought this would give UB, due the fact that I'm passing a r-value to the function and it doesn't have a memory address assigned, but this outputs:

aello

Is there something that I'm missing here?

Aucun commentaire:

Enregistrer un commentaire