C++核心准则讨论:按值返回容器(依靠移动或复制省略高效率)

2020-12-31 14:55:44 浏览数 (3)

Discussion: Return containers by value (relying on move or copy elision for efficiency)

讨论:按值返回容器(依靠移动或复制省略高效率)

Reason(原因)

To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime.

为了简化代码并消除对显式内存管理的需求。使物体进入周围的范围,从而延长其使用寿命。

See also: F.20, the general item about "out" output values

另请参见:F.20 输出结果时更应该使用返回值而不是输出参数

Example(示例)

代码语言:javascript复制
vector<int> get_large_vector()
{
    return ...;
}

auto v = get_large_vector(); //  return by value is ok, most modern compilers will do copy elision
Exception(例外)

See the Exceptions in F.20.

参加F.20中的例外项目。

Enforcement(实施建议)

Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a unique_ptr).

检查是否有从函数返回的指针和引用,并查看它们是否已分配给资源句柄(例如,分配给unique_ptr)。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-return-containers-by-value-relying-on-move-or-copy-elision-for-efficiency

0 人点赞