相关疑难解决方法(0)

std :: move(*this)是一个好模式吗?

为了使这个代码与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)但是,如果 …

c++ this lvalue move-semantics c++11

31
推荐指数
1
解决办法
3129
查看次数

在c ++中返回*这是安全的吗?

我想知道从函数返回*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)

是否会出现内存泄漏?

c++ pointers memory-leaks

4
推荐指数
1
解决办法
119
查看次数

标签 统计

c++ ×2

c++11 ×1

lvalue ×1

memory-leaks ×1

move-semantics ×1

pointers ×1

this ×1