gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:41:50 25 4
gpt4 key购买 nike

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

我现在需要拿走其中一个,在不同的类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com