为什么"out variable pattern"在 C++ 中如此频繁地使用?

Why is the "out variable pattern" used so often in c++?

本文关键字:variable out pattern 为什么 C++      更新时间:2023-10-16

我不知道模式的实际名称

我通常不写c++代码,但每次我读它时,我都会看到相同的模式一遍又一遍。

我刚刚在虚幻引擎4中又发现了它,看起来像这样

FVector CameraLoc;
FRotator CameraRot;
GetActorEyesViewPoint(CameraLoc, CameraRot);

我一直很讨厌这种模式,因为我永远不知道哪个参数被改变了,然后有时函数期望对象被正确初始化。

为什么要使用这个模式?把它包装在一个结构体中不是更好吗?

struct ActorEyesViewPoint {
    FVector CameraLoc;
    FRotator CameraRot;
};

ActorEyesViewPoint GetActorEyesViewPoint();

此模式用于防止从函数返回时不必要的对象复制。这基本上是RVOs的显式版本(http://en.wikipedia.org/wiki/Return_value_optimization)

注意,在c++ 11中不再需要移动语义

这种模式的一个优点是可以将派生类传递给接受基类的函数。

如果你有

class A {  };
class B : public A {  };
void foo(A* a);
A bar();

需要一个B类的对象,foo是有用的,但bar不是。