【发布时间】:2015-10-04 20:11:45
【问题描述】:
考虑这个类:
template<typename T> struct pooled_resource: T{
template<typename... Args> pooled_resource(std::list<T>& pool, Args&&... args):
T(select_resource(pool, std::forward<Args>(args)...)), pool(pool){
if(!pool.empty()) pool.pop_front();
}
~pooled_resource(){
pool.push_front(static_cast<T&&>(*this));
}
private:
std::list<T>& pool;
template<typename... Args> static T select_resource(std::list<T>& pool, Args&&... args){
if(pool.empty())
return T(std::forward<Args>(args)...);
else
return std::move(pool.front());
}
};
它允许创建具有池化资源但在语义上等同于非池化版本的变量:
std::list<std::vector<int>> pool;
using pooled_vector = pooled_resource<std::vector<int>>;
{
pooled_vector a(pool); //pool is empty, allocate new resources
{ pooled_vector b(pool, 100); } //allocate again, but then release to pool as b goes out of scope
pooled_vector c(pool); //reuse b's resources
assert(c.size() == 100);
}
我的实际问题是,对于上面的简单情况,一切正常,并且调用了池资源的移动构造函数。但是,我得到了另一个类,它没有调用移动构造函数,而是调用了复制构造函数。准确地说,该类是boost::compute::vector,它确实声明了一个移动构造函数,该构造函数似乎在boost::compute::vector<int> a; boost::compute::vector<int> b(std::move(a)); 等简单情况下工作。
我不知道为什么会发生这种情况,也不知道如何诊断:关于实际使用移动构造函数的规则,我缺少什么?
【问题讨论】:
-
如果未启用相应的标志,您所展示的动作实际上可能是副本。
-
@Puppy “适当的标志”?
-
@Puppy 你的意思是,已启用
-
只有在未设置适当的宏 (
BOOST_COMPUTE_NO_RVALUE_REFERENCES) 时才定义声明的移动构造函数。如果设置了此项,则没有移动构造函数,但您的代码无论如何都会编译,因为在这种情况下移动可以成为副本。因此,这不是一个有用的试金石。 -
我已经检查过
BOOST_COMPUTE_NO_RVALUE_REFERENCES没有定义。