C++通过引用多次返回
我一直在使用引用返回来尝试加速我的代码并避免多次昂贵的复制操作。
我有一个如下所示的访问成员函数:
std::string const& access_element(int index) const;
如果我有另一个调用 access_element() 的成员函数,我是否还需要通过引用返回该函数?
例如。
float const& access_element2(int index) const {
return atof(access_element(index));
}
相对
float access_element2(int index) {
return atof(access_element(index));
}
I have been using return by reference to try to speed up my code and avoid multiple expensive copy operations.
I have an access member function that looks like this:
std::string const& access_element(int index) const;
If I have another member function that calls access_element(), do I need to also return that by reference?
For instance.
float const& access_element2(int index) const {
return atof(access_element(index));
}
versus
float access_element2(int index) {
return atof(access_element(index));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在通过引用返回一个临时值。
在这种情况下,您的瓶颈在于 atof,而不是返回副本。
atof 返回一个临时值。如果您的目的是通过引用返回来加快速度,则应该返回一个成员对象,或通过引用返回的成员对象(如向量项)的成员对象。
You are returning by reference a temporary value.
In this case your bottleneck is in atof, not in returning a copy.
atof return a temporary value. If your intention is to speed up with a return by reference, you should return a member object, or a member object of a member object (like a vector item) that is returned by reference.
这是一篇好文章:想要速度吗?按值传递。
此外,您确实需要小心通过引用返回。引用就像指针一样,您可以获得不合法使用的悬空引用。以下内容具有未定义的行为:
此外,当传递像
float
这样的基本类型时,通常最好只复制它们,因为传递指针意味着您将复制指针,这不太可能比复制值本身。这个答案对于通过引用与值获取参数有一个很好的经验法则:https://stackoverflow.com/a/1567186/365496通过 const & 而不是通过值传递的另一个原因是,如果制作副本可能需要堆内存分配。此类副本可能会失败,因此最好通过引用传递以避免出现错误的可能性。
Here's a good article: Want Speed? Pass by Value.
Also you really need to be careful with returning by reference. References are like pointers in that you can get dangling references which aren't legally usable. The following has undefined behavior:
Also, when passing primitive types like
float
it's usually better to just copy them, because passing a pointer means you'll be copying a pointer instead, which is unlikely to be faster than copying the value itself. This answer has a good rule of thumb for taking parameters by reference vs. value: https://stackoverflow.com/a/1567186/365496Another reason to pass by
const &
instead of by value is if making a copy could require heap memory allocations. Such copies could fail and so it's better to pass by reference to avoid that error possibility.