c++ - 在双端队列之间移动唯一指针

标签 c++ c++11

我有一个容器类,用于存放一些指向对象的唯一指针。

我现在需要拿走其中一个,在不同的类(class)中对它们进行一些处理,然后移交给另一个类(class)(并在某个时候回收它们并将它们放回容器中)。

下面是代码的概要。但是,我对使用函数移动唯一指针的正确方法感到困惑:

using uptrPod =  unique_ptr<Pod>;
using dqUptrPods = deque<uptrPods>;

class Container {
public:
    Container() :
        n_elements_( 500 )
    {
        for ( auto i = 0; i < n_elements_; i++ ) {
        free_pods_.push_back( uptrPod( new Pod()) );
    }

    const uptrPod&& getPod() {
        auto up_pod= std::move( free_pods_[0] );
        free_pods_.erase( free_pods_.begin() );
        return up_pod;
    }

    void returnPod( const uptrPod&& up_pod ) {
        free_pods_.push_back( up_pod );
    }

private:
    long n_elements_;
    dqUptrPods free_pods_;
};

class PodTracker {

    void addPod( const uptrPod&& up_pod ) { dq_pods_.pushback( up_pod ); }
    dqUptrPods dq_pods_;
};

class PodHandler {

    void movePod() {
        up_pod = std::move( container_->getPod() );

        /// do stuff with pod

        pod_tracker_->addPod( up_pod );
    }

    Container* container_;
    PodTracker* pod_tracker_;
};

我收到错误:

cannot bind std::unique_ptr l value to const uptrPod&& { aka const std::unique_ptr &&

如何在类之间传递指针?

最佳答案

按值传递/返回std::unique_ptr实例,并显式使用std::move:

uptrPod getPod() { 
    auto up_pod= std::move( free_pods_[0] ); 
    free_pods_.erase( free_pods_.begin() );
    return up_pod;
}

void returnPod( uptrPod up_pod ) { 
    free_pods_.push_back( std::move(up_pod) );        
}

class PodTracker{
    void addPod(uptrPod up_pod) { dq_pods_.push_back(std::move(up_pod)); }
    dqSptrPods dq_pods_;
};

void movePod() {

    // `std::move` is not necessary here, as `getPod()`
    // is already a temporary (rvalue)
    auto up_pod = container_->getPod();

    /// do stuff with pod

    pod_tracker_->addPod( std::move(up_pod) ) ;   
}

example on wandbox


请注意,const 右值引用 没有多大意义 - 右值引用。

The main purpose of rvalue references is to allow us to move objects instead of copying them. And moving the state of an object implies modification. As a result, the canonical signatures for the move constructor and the move assignment operator both take its argument as a non-const rvalue reference.

(来自:"What are const rvalue references good for?")

关于c++ - 在双端队列之间移动唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737723/

相关文章:

c++ - 为什么我不能直接在临时对象上调用 operator() ?

c++ - YUV转RGB颜色转换代码如何优化

c++ - C++ 中的线程池/队列系统

c++ - 在这种情况下如何正确使用 std::enable_if

c++ - 如何确定存储在数组中的项目数?

c++ - Aerospike 没有回应

c++ - 触发异常时应该如何记录?

c++ - 具有显式构造函数的类是否需要 piecewise_construct in emplace?

c++ - auto&& 变量不是右值引用

c++ - 如何在 C++11 中将 vector 与引用类型实例对象一起使用?