簡體   English   中英

如果右值引用超出范圍會怎樣?

[英]What happens if a rvalue reference goes out of scope?

我正在嘗試移動語義,我想知道如果右值引用超出范圍會發生什么。 使用以下代碼,如果我將std :: move左值移入,則會遇到運行時問題

function(T t) with t = std::move(lvalue) --> SEGFAULT OR double free

但不成

function(T &&t) with t = std::move(lvalue) --> OK

有人知道為什么嗎?

另外,如果交換main()中的兩個代碼塊,則會得到不同的運行時錯誤0_o

// Compile with:
// g++ move_mini.cpp -std=c++11 -o move_mini
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <list>
#include <utility>
using namespace std;

int num_copied;

class T{
    public:
    T() : a(nullptr), b(nullptr){};

    T(const T &t) : a(new string(*t.a)), 
                    b(new string(*t.b)){
        num_copied++;
        };

    T(T &&t){
        *this = move(t);
        };

    T(string s1, string s2){
        this->a = new string(s1);
        this->b = new string(s2);
        };

    ~T(){
        delete this->a;
        delete this->b;
        };

    T& operator=(const T &lhs){
        num_copied++;
        delete this->a;
        delete this->b;
        this->a = new string(*lhs.a);
        this->b = new string(*lhs.b);
        return *this;
        };

    T& operator=(T &&lhs){
        swap(this->a, lhs.a);
        swap(this->b, lhs.b);
        return *this;
        };

    string *a;
    string *b;
    };

void modify1(T t){
    }

void modify3(T &&t){
    }

int main(){
    cout << "##### modify1(T t) #####" << endl;
    T t_mv1("e", "asdsa");
    num_copied = 0;
    modify1(move(t_mv1));
    cout << "t = move(t_mv)          copies " << num_copied << " times." << endl;
    cout << endl;

    cout << "##### modify3(T &&t) #####" << endl;
    T t_mv3("e", "aseeferf");
    num_copied = 0;
    modify3(move(t_mv3));
    cout << "t = move(t_mv)          copies " << num_copied << " times." << endl;
    cout << endl;

    return 0;
    }

讓我們從這里開始:

modify1(move(t_mv1));

為了構造modify1的參數,使用T的move構造函數:

T(T &&t){
    *this = move(t);         // <--- this calls move assignment operator
};

注意上面的注釋行。 到那個時候, *this對象的兩個數據成員被默認初始化,這對於指針意味着它們留下了不確定的值。 接下來,將移動分配運算符稱為:

T& operator=(T &&lhs){
    swap(this->a, lhs.a); // reads indeterminate values and invokes
    swap(this->b, lhs.b); // undefined behaviour
    return *this;
};

現在,當modify1返回時,參數對象被銷毀, T的析構函數對未初始化的指針進行delete ,從而再次調用未定義的行為

我沒有看過第二部分(帶有modify3 ),但是我懷疑正在發生類似的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM