简体   繁体   English

构造本地对象-const引用

[英]Constructing local objects - const references

Recently I have seen following code snippet during a code review: 最近,我在代码审查中看到了以下代码片段:

const QString& temp("some text");
const QString& temp1("some text1");

(...)

if (temp == "whatever")
{
}

// etc

Since such temporaries look a bit odd to me, I just wanted to ask if anyone can explain what are the pros/cons of constructing objects this way? 由于这样的临时对象对我来说有些奇怪,我只想问问是否有人可以解释以这种方式构造对象的利弊? I would just go for the const objects - do I miss anything there? 我只想去看const对象-我会在那里错过任何东西吗?

You could have chosen a better example. 您可以选择一个更好的例子。

A few advantages of using ref variables would be: 使用ref变量的一些优点是:

1) the ref name may add some meaning/documentation to the code. 1)引用名称可能会在代码中添加一些含义/文档。 For example: 例如:

const QString& protocol_start("ABC1RQA666T");

The string "ABC1RQA666T" is pretty meaningless but protocol_start may give more of a clue as to what the string represents. 字符串“ ABC1RQA666T”是毫无意义的,但是protocol_start可能会提供有关该字符串代表什么的更多线索。

2) If the reference is used a number of times then it might be more convenient to use the reference. 2)如果多次使用参考,则使用参考可能会更方便。

3) Using the reference is fairly 'cheap' because after all it is just an alias. 3)使用引用相当“便宜”,因为毕竟它只是一个别名。

But in some code you might see instances where the ref is not referred to multiple times and the ref name adds little extra documentation value so in those cases it is not so useful. 但是在某些代码中,您可能会看到没有多次引用引用且引用名称添加很少的附加文档值的情况,因此在这种情况下,它不是那么有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM