在C ++中返回std :: vector的有效方法 [英] Efficient way to return a std::vector in c++

查看:278
本文介绍了在C ++中返回std :: vector的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数中返回std :: vector时,要复制多少数据,以及将std :: vector放在免费存储中(在堆上)并返回指针的优化有多大? :

How much data is copied, when returning a std::vector in a function and how big an optimization will it be to place the std::vector in free-store (on the heap) and return a pointer instead i.e. is:

std::vector *f()
{
  std::vector *result = new std::vector();
  /*
    Insert elements into result
  */
  return result;
} 

比:

std::vector f()
{
  std::vector result;
  /*
    Insert elements into result
  */
  return result;
} 

推荐答案

在C ++ 11中,这是首选方式:

In C++11, this is the preferred way:

std::vector<X> f();

即按值返回。

对于C ++ 11, std :: vector 具有移动语义,这意味着 local在函数中声明的向量将在返回时被移动,在某些情况下,甚至编译器也可以忽略该移动。

With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

这篇关于在C ++中返回std :: vector的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆