【问题标题】:copy constructor called instead of move constructor, why?调用复制构造函数而不是移动构造函数,为什么?
【发布时间】: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&lt;int&gt; a; boost::compute::vector&lt;int&gt; b(std::move(a)); 等简单情况下工作。

我不知道为什么会发生这种情况,也不知道如何诊断:关于实际使用移动构造函数的规则,我缺少什么?

【问题讨论】:

  • 如果未启用相应的标志,您所展示的动作实际上可能是副本。
  • @Puppy “适当的标志”?
  • @Puppy 你的意思是,已启用
  • 只有在未设置适当的宏 (BOOST_COMPUTE_NO_RVALUE_REFERENCES) 时才定义声明的移动构造函数。如果设置了此项,则没有移动构造函数,但您的代码无论如何都会编译,因为在这种情况下移动可以成为副本。因此,这不是一个有用的试金石。
  • 我已经检查过BOOST_COMPUTE_NO_RVALUE_REFERENCES 没有定义。

标签: c++11 move


【解决方案1】:

所以问题是池资源类中的一个愚蠢错误。这是它的草图:

template<typename T, typename Allocator = DefaultAllocator> struct Resource{
    /*...*/
    Resource(Resource<T>&& o){ /*...*/ }
}

问题在于移动构造函数的参数类型为Resource&lt;T, DefaultAllocator&gt;。由于我使用了一些自定义分配器,实际上没有模板移动构造函数可用于通用Allocator,而只有通用类型T 和分配器DefaultAllocator。该修复只需要省略移动构造函数的所有模板规范:

Resource(Resource&& o){ /*...*/ }

希望这可以节省别人的下午。

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 2013-04-25
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2019-11-07
    相关资源
    最近更新 更多