【问题标题】:How can I avoid extra copying when constructing a vector to be returned?在构造要返回的向量时如何避免额外的复制?
【发布时间】:2016-11-02 01:04:11
【问题描述】:

这里是 C++ 新手!我写了一个代码,它正在考虑一个由CITIES 向量组成的WORLD。这个世界会更新nbTimeStep 次。这是我的代码外观的粗略摘要。为便于阅读,所有类名全部大写。

// Definition of Class `WORLD`
class WORLD
{
  private:
    vector<CITY> cities;
  public:
    void AddCity(CITY& city)
    {
      cities.push_back(city);
    }
}

// In main

WORLD world(Arguments);
for (int time_step=0 ; time_step < nbTimeSteps ; time_step++)
{
   WORLD EmptyWorld;
   world = ReCreateWorld(world,EmptyWorld); // The object `EmptyWorld` will be returned after being 'filled' with cities.
}

函数ReCreateWorld定义为

WORLD& ReCreateWorld(WORLD& OldWorld, WORLD& NewWorld)
{
  for (int city_index=0 ; city_index < NbCities ; city_index++)
  {
    /* Long Process of creating a single 'CITY' called `city`
    ...
    ...
    */


    // Add the city to the list of cities (process I am trying to optimize)
    NewWorld.AddCity(city);
  }
    return NewWorld;
}

分析后,我看到大约 20% 的时间进程在方法 AddCity 中。我从不需要任何给定CITY 的两个实例,因此浪费大量时间复制每个城市似乎很愚蠢。 我该如何解决这个问题?


有些人可能想评论我将一个空的WORLD 传递给ReCreateCities,因为它不是很优雅。我这样做主要是为了强调慢速复制部分发生在cities.push_back(city); 行,而不是ReCreateWorld 返回其WORLD 时。

【问题讨论】:

  • 答案在某种程度上取决于CITY 的样子。可以移动吗(是否有移动构造函数)?
  • 如果您不确定什么是移动构造函数,CITY 的移动构造函数将是一个声明为 CITY(CITY&amp;&amp;); 的构造函数,带有两个 &。

标签: c++ performance vector push-back


【解决方案1】:

就像 Justin 和 Daniel 建议的那样,使用 move c-tor。老派的方法是使用指针,例如 typedef std::unique_ptr CITY_PTR; std::vector 城市; 并且只推送城市的指针。

您可以尝试类似于 emplace http://www.cplusplus.com/reference/vector/vector/emplace/ 的方法,它直接转发 c-tor 参数。

【讨论】:

猜你喜欢
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2018-03-09
  • 2021-12-04
  • 1970-01-01
  • 2012-01-26
相关资源
最近更新 更多