简体   繁体   中英

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?

You could have chosen a better example.

A few advantages of using ref variables would be:

1) the ref name may add some meaning/documentation to the code. 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.

2) If the reference is used a number of times then it might be more convenient to use the reference.

3) Using the reference is fairly 'cheap' because after all it is just an alias.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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