构造函数接受字符串引用。馊主意? [英] Constructors accepting string reference. Bad idea?

查看:157
本文介绍了构造函数接受字符串引用。馊主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它被认为是一个坏主意/糟糕的设计,有一个类接受一个引用,如下面的构造函数:

It's considered a bad idea/bad design, have a class with a constructor accepting a reference, like the following?

class Compiler
{
public:
  Compiler( const std::string& fileName );
  ~Compiler();
//etc
private: 
  const std::string& m_CurrentFileName;
};

还是应该使用值?
我实际上关心性能。

or should I use values? I actually do care about performance.

推荐答案

如果在这种情况下使用了value参数,在类中引用一个临时的,在将来的某个时候会变得无效。

If you used a value parameter in this case, you would have a reference in the class to a temporary, which would become invalid at some point in the future.

这里的坏主意可能是存储一个引用作为成员在类中。它几乎总是更简单,更正确的存储一个值。在这种情况下,传递构造函数const引用是正确的事情。

The bad idea here is probably storing a reference as a member in the class. It is almost always simpler and more correct to store a value. And in that case, passing the constructor a const reference is the right thing to do.

至于性能,你应该只关心这个 ,您只能通过分析您的代码找到。您应该始终先编写代码,以确保正确性,其次是为了清楚,最后是为了性能。

And as for performance, you should only care about this where it matters, which you can only find out by profiling your code. You should always write your code firstly for correctness, secondly for clarity and lastly for performance.

这篇关于构造函数接受字符串引用。馊主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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