且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 C++11 中的函数调用返回 std::vector 的正确方法(移动语义)

更新时间:2022-06-06 09:44:11

如果您使用的是与 C++0x 兼容的编译器和标准库,您可以从第一个示例中获得更好的性能什么都不做强>.get_vector(_n, _m) 的返回值是一个临时值,std::vector 的移动构造函数(一个接受右值引用的构造函数)将被自动调用您无需再做进一步的工作.

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.