简体   繁体   English

返回 stl 容器的正确方法

[英]Proper way to return stl container

A lot of times, we need to return a container constructed inside a function.很多时候,我们需要返回一个在函数内部构造的容器。 Say I have a function to get all primes in some range.假设我有一个函数可以获取某个范围内的所有素数。

std::vector<int> getPrimes() {
    std::vector<int> primes;
    ...
    reutrn primes;
}

This seems need to copy all primes to the returned object.这似乎需要将所有素数复制到返回的对象中。 Then pointers are needed.然后需要指针。

// =================Wrong code=================
// std::vector<int> *getPrimes() {
//     std::vector<int> primesptr;
//     ...
//     reutrn &primesptr;
// }

But apparently local variables cannot be returned.但显然不能返回局部变量。 So the new operator can be used.所以可以使用new运算符。

std::vector<int> *getPrimes() {
    std::vector<int> *primesptr = new std::vector<int>();
    ...
    reutrn primesptr;
}

Finally, this meets the need.最后,这符合需要。 But it's ugly and complicated (because of the usage of pointers).但它既丑陋又复杂(因为使用了指针)。 So what's the recommended way to return STL containers constructed inside a function?那么返回在函数内部构造的 STL 容器的推荐方法是什么? Moreover, if I return the STL container by value, will it be optimized so that only a constant amount of values or pointers are copied (instead of copying every element in the container)?此外,如果我按值返回 STL 容器,是否会对其进行优化,以便仅复制恒定数量的值或指针(而不是复制容器中的每个元素)?

If you're using a modern compiler, just use your original code;如果您使用的是现代编译器,只需使用您的原始代码; NRVO (Named Return Value Optimization), a form of copy elision , is performed by most modern compilers in the simple case you're demonstrating. NRVO(命名返回值优化)是一种复制省略形式,在您演示的简单情况下由大多数现代编译器执行。

If for some reason you can't rely on this, and profiling shows this is a big problem on this crappy compiler you're using, you can, if you insist, explicitly do:如果由于某种原因你不能依赖它,并且分析表明这是你正在使用的这个蹩脚编译器的一个大问题,你可以,如果你坚持,明确地做:

std::vector<int> getPrimes() {
    std::vector<int> primes;
    ...
    return std::move(primes);
}

This will prevent NRVO (so you'll definitely end up move-constructing the return value while destructing the emptied local variable), but move-construction of a vector is a fixed cost unrelated to the vector 's size (a handful of pointer and size_t assignments, the main backing array's storage is untouched).这将防止 NRVO(因此您肯定会在销毁清空的局部变量时移动构造返回值),但是vector移动构造是固定成本,与vector的大小无关(少量指针和size_t分配,主后备阵列的存储未受影响)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM