相关疑难解决方法(0)

我应该std ::在移动构造函数中移动shared_ptr吗?

考虑:

#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

class Gizmo
{
public:
    Gizmo() : foo_(shared_ptr<string>(new string("bar"))) {};
    Gizmo(Gizmo&& rhs); // Implemented Below

private:
    shared_ptr<string> foo_;
};

/*
// doesn't use std::move
Gizmo::Gizmo(Gizmo&& rhs)
:   foo_(rhs.foo_)
{
}
*/


// Does use std::move
Gizmo::Gizmo(Gizmo&& rhs)
:   foo_(std::move(rhs.foo_))
{
}

int main()
{
    typedef vector<Gizmo> Gizmos;
    Gizmos gizmos;
    generate_n(back_inserter(gizmos), 10000, []() -> Gizmo
    {
        Gizmo ret;
        return ret;
    });

    random_shuffle(gizmos.begin(), gizmos.end());

}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,有两个版本Gizmo::Gizmo(Gizmo&&) …

c++ shared-ptr rvalue-reference c++11

14
推荐指数
3
解决办法
1万
查看次数

标签 统计

c++ ×1

c++11 ×1

rvalue-reference ×1

shared-ptr ×1