为了使这个代码与C++ 11引用限定符按预期工作,我必须引入一个std::move(*this)听起来不对的代码.
#include<iostream>
struct A{
void gun() const&{std::cout << "gun const&" << std::endl;}
void gun() &&{std::cout << "gun&&" << std::endl;}
void fun() const&{gun();}
void fun() &&{std::move(*this).gun();} // <-- is this correct? or is there a better option
};
int main(){
A a; a.fun(); // prints gun const&
A().fun(); // prints gun&&
}
Run Code Online (Sandbox Code Playgroud)
有些事情听起来不对劲.有std::move必要吗?这是推荐使用吗?目前,如果我不使用它,我会遇到gun const&两种情况,这不是预期的结果.
(似乎*this总是隐式和左值引用,这是有道理的,但然后是逃避使用的唯一方法move)
用clang 3.4和测试gcc 4.8.3.
编辑:这是我从@hvd回答中理解的:
1)std::move(*this)在语法和概念上是正确的
2)但是,如果 …
我想知道从函数返回*this是否安全.这个问题显示了一些你可以做到的方法,我的问题是这个例子:
struct test {
string t;
string b;
public:
test& A(string test) { this->t=test; return *this; }
test& B(string test) { this->b=test; return *this; }
};
int main() {
auto a = test().A("a").B("b").A("new a");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是否会出现内存泄漏?