我有一个容器类,用于存放一些指向对象的唯一指针。
我现在需要拿走其中一个,在不同的类(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) ) ;
}
请注意,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.
关于c++ - 在双端队列之间移动唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737723/