我正在试验移动语义,我想知道如果右值引用超出范围会发生什么。使用以下代码,如果我 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;
}