应该通过const引用传递小的简单结构吗? [英] Should small simple structs be passed by const reference?

查看:149
本文介绍了应该通过const引用传递小的简单结构吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直被教导非原始类型应该通过const引用而不是通过值尽可能传递,即:

I have always been taught that non-primitive types should be passed by const reference rather than by value where possible, ie:

void foo(std::string str);//bad
void foo(const std::string &str);//good

但是我想今天,也许实际上一些简单的用户定义类型可能更好地通过值传递,例如:

But I was thinking today that maybe actually some simple user defined types may actually be better passed by value eg:

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?

我的想法是通过引用传递Vector2,它实际上比传递值编译器现在使用指针并取消引用来访问const Vector2& pos版本?

My thought is that by passing the Vector2 by reference, it is actually more expensive than passing by value since the compiler is now using a pointer and dereferencing to access the const Vector2 &pos version?

这是否是这种情况?是简单的对象最好通过价值吗?

Is this the case? Are simple objects best off passed by value? Where should the line be drawn?

推荐答案

是的,简单对象应该通过值传递。线必须根据架构绘制。如有疑问,请查看个人资料。

Yes, simple objects should be passed by value. The line has to be drawn according to the architecture. If in doubt, profile.

这篇关于应该通过const引用传递小的简单结构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆