Skip to content

Instantly share code, notes, and snippets.

@baiwfg2
Created March 8, 2018 11:36
Show Gist options
  • Save baiwfg2/ebd78f340f7b10a215e3b5356de74010 to your computer and use it in GitHub Desktop.
Save baiwfg2/ebd78f340f7b10a215e3b5356de74010 to your computer and use it in GitHub Desktop.
identify some subtle effect on copy or move of std::move(lvalue reference) and const
#include <iostream>
#include <string>
using namespace std;
struct X {
public:
X(string s): _s(s) { cout << "x ctor\n"; }
X(X&& x): _s(std::move(x._s)) { cout << "x move ctor\n"; } //define this will implicitly delete the copy ctor
//X(const X& x): _s(x._s) { cout << "x copy ctor\n"; }
void print() {
cout << "x::print:" << _s << endl;
}
string _s;
};
void f1(X& x) {
//auto& x1 = std::move(x);
const auto x2 = std::move(x);//must use const ! This will move original data to x2
}
void f2(const X& x) {
//auto& x1 = std::move(x);//this will not call copy ctor or move ctor
auto x2 = std::move(x); // this will call copy ctor, so it won't affect original(Seems that compiler turn `move` into `copy`)
}
void t1() {
X x("a");
f1(x);
x.print();
}
///////////////////////////////
class T {
public:
T() { cout << "t ctor\n"; }
T(string s) { cout << "t ctor2\n"; }
T(T&& t) { cout << "t move ctor\n"; }
T(const T&& t) { cout << "t copy ctor\n"; }
string _s;
};
void g(const T& t) {
cout << "g begin\n";
auto t2 = std::move(t);
cout << "------\n";
T t1;
T t3 = std::move(t1); // t1 is not a reference, so `move` Operation will definitely move its data to t3
}
void t2() {
T t1;
g(t1);
}
//////////////////////////////////////
void h1(const string& i) { //whether i is const& or & really matters
string j = std::move(i);//false move, actually copy
}
void h2(string& i) {
string j = std::move(i);//real move
}
void t_string() {
string s = "ab";
h1(s);
cout << "after h1, s=" << s << endl;
s = "abcd";
h2(s);
cout << "after h2, s=" << s << endl;
}
int main(int argc, char *argv[])
{
t1();
//t_string();
//t2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment