从纯虚函数返回引用可以吗? [英] Is it ok to return reference from pure virtual function?

查看:88
本文介绍了从纯虚函数返回引用可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class I {
public:
  virtual std::wstring const& GetName() const = 0;
};

通常,实现此接口的客户端将其名称包含在其主体内.而且一切正常.但是有时,"GetName"的结果是在函数执行期间计算的.使用静态变量存储结果不是一个好主意.但是按值返回需要额外的性能开销.

Usually clients which implement this interface contain their name inside their body. And everything works just fine. But sometimes the result of 'GetName' is calculated during function execution. Using static variable to store result is not a very good idea. But returning by value requires additional performance overhead.

那么如何解决这个问题?谢谢.

So how this problem could be solved? Thanks.

推荐答案

但是按价值返回需要额外的性能开销.

But returning by value requires additional performance overhead.

这不是事实.编译器通常可以使用返回值优化取消该副本.

This is not true. The compiler will very often be able to elide the copy using Return Value Optimization.

这篇关于从纯虚函数返回引用可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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