赋予另一个向量内存的std :: vector所有权?

时间:2019-07-25 20:04:15

标签: c++ optimization vector

我有一个看起来像这样的构造函数:

with ancestors as (
  select 1 as level, id_person, ancestor_id_person, name, wealth
  from test_people
  where id_person = 1
  UNION ALL
  select parent.level + 1, child.id_person, child.ancestor_id_person, child.name, child.wealth
  from ancestors as parent,
  test_people as child 
  where parent.id_person = child.ancestor_id_person
)
select T.id_person, A.ancestor_id_person, A.name, T.name, T.ancestor_id_person
from test_people as T
left outer join ancestors as A on T.ancestor_id_person = max(A.ancestor_id_person, A.id_person)

但是,Thing::Thing(std::vector<uint8> & data){ m_data = data; // m_data is also a vector<uint8> // do other stuff } 拥有相当大的内存,并且我不想复制它,而是希望data放弃它给data,因为调用者永远不会构造此对象后需要它。用C ++做到这一点的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

您可以使用移动分配运算符。

m_data = std::move(data);

最好将参数类型更改为值或右值引用,以使函数用户对输入参数的内容已被移动不感到惊讶。

Thing::Thing(std::vector<uint8>&& data){
    m_data = std::move(data);
    // do other stuff
}

鉴于此,调用函数将意识到他们需要传递右值引用,而对内容的移动不会感到惊讶。

最好使用m_data初始化data,而不要分配给它。

Thing::Thing(std::vector<uint8>&& data) : m_data(std::move(data))
{
    // do other stuff
}