Fir*_*cer 18 c++ function pass-by-reference user-defined-types
我一直被告知非原始类型应该通过const引用传递,而不是通过值传递,即:
void foo(std::string str);//bad
void foo(const std::string &str);//good
Run Code Online (Sandbox Code Playgroud)
但我今天在想,也许实际上一些简单的用户定义类型实际上可能更好地通过值传递,例如:
class Vector2
{
public:
float x, y;
...constructors, operators overloads, utility methods, etc...
};
void foo(Vector2 pos);
void foo(const Vector2 &pos);//is this really better than by value?
void foo(float x, float y);//after all isn't by value effectively doing this?
Run Code Online (Sandbox Code Playgroud)
我的想法是,通过引用传递Vector2,它实际上比传递值更昂贵,因为编译器现在使用指针和解除引用访问const Vector2&pos版本?
是这样的吗?最简单的对象是否最符合价值?该线应该在哪里绘制?