正确的方式(移动语义)从C ++ 11中的函数调用返回std :: vector [英] Proper way (move semantics) to return a std::vector from function calling in C++11

查看:642
本文介绍了正确的方式(移动语义)从C ++ 11中的函数调用返回std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想填充std :: vector(或其他一些STL容器):

  class Foo {
public:
Foo(int _n,const Bar& _m);
private:
std :: vector< Foo> fooes_;
}

/ p>

  std :: vector< Foo> get_vector(int _n,const Bar& _m){
std :: vector< Foo> ret;
... //根据参数填充ret
return ret;
}

Foo :: Foo(int _n,const Bar& _m):fooes_(get_vector(_n,_m){}
/ pre>

2。更好的性能,更差的外观。



< void fill_vector(int _n,const Bar& _m,std :: vector< Foo&& _ret){
... //根据参数填充ret
}

Foo :: Foo(int _n,const Bar& _m){fill_vector(_n,_m,fooes_);}

可以使用C ++ 0x从第一个例子中重写 get_vector 函数(移动语义特性等等),以避免冗余复制和构造函数调用?

解决方案

如果使用C ++ 0x兼容的编译器和标准库,第一个例子不执行任何操作的性能。 get_vector(_n,_m)的返回值是一个临时变量, c $ c> std :: vector (一个带有右值引用的构造函数)将自动调用,无需进一步的工作。



一般来说,非库编写器不需要直接使用右值引用;你会自动获得一大块的好处。


I want to fill std::vector (or some other STL container):

class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}

1.Good looking ctor, expensive performance

std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}

2. Better performance, worse looking ctor

void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?

解决方案

If you're using a C++0x-compatible compiler and standard library, you get better performance from the first example without doing anything. The return value of get_vector(_n, _m) is a temporary, and the move constructor for std::vector (a constructor taking an rvalue reference) will automatically be called with no further work on your part.

In general, non-library writers won't need to use rvalue references directly; you'll just reap a decent chunk of the benefits automatically.

这篇关于正确的方式(移动语义)从C ++ 11中的函数调用返回std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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