简体   繁体   中英

Questions about right value reference in C++

#include <iostream>

using namespace std;

void swap(int& a, int& b) 
{

    cout << "address of a: " << &a << " value of a: " << a << endl;
    cout << "address of b: " << &b << " value of b: " << b << endl;

    int tmp{move(a)};

    cout << "address of tmp: " << &tmp << " value of tmp: " << tmp << endl;

    a = move(b);
    b = move(tmp);

    cout << "address of a: " << &a << " value of a: " << a << endl;
    cout << "address of b: " << &b << " value of b: " << b << endl;
    
}

void swap_no_move(int& a, int& b)
{

    cout << "address of a: " << &a << " value of a: " << a << endl;
    cout << "address of b: " << &b << " value of b: " << b << endl;

    int tmp{ a };

    cout << "address of tmp: " << &tmp << " value of tmp: " << tmp << endl;

    a = b;
    b = tmp;

    cout << "address of a: " << &a << " value of a: " << a << endl;
    cout << "address of b: " << &b << " value of b: " << b << endl;

}

int main() {
    
    int a = 10;
    int b = 5;

    swap(a, b);

    cout << endl;

    int c = 10;
    int d = 5;

    swap_no_move(c, d);

    cin.get();

    return 0;
}

在此处输入图片说明

I have two swap functions: swap and swap_no_move. According to what I read from the book, there should be no "copy" in function swap which means the address of tmp should be the same for tmp and an in function swap. However, the output I got shows there is no difference between these two functions, did I do something wrong?

The definition

int tmp{move(a)};

doesn't move the reference or the variable a itself. It creates a brand new variable tmp which the compiler allocates space for. Then the value of a is moved into tmp .

And since moving int values can't really be done, it's exactly the same as

int tmp = a;

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