Fabian
Fabian

Reputation: 4211

Should I use a reference?

I have a class containing an implementation pointer. Therefore, in some functions, I refer to a member of the implementation several times. Is it a good idea to write

// approach 1
std::string & str = m_pImpl->m_str;
str.clear();
str += "blablabla";
// ...
return str.c_str();

once and use the reference to save the pointer indirection, or should I save the reference variable (This is always 4 or 8 bytes, like a pointer, right?)?

// approach 2
m_pImpl->m_str.clear();
m_pImpl->m_str += "blablabla";
// ...
return m_pImpl->m_str.c_str();

In my usecase the variable m_pImpl->m_str is used about 10 to 20 times. I am afraid I can hardly profile the performance difference between these two approaches. Does anybody know or can anybody test it makes a difference? Does this depend on how often I use the variable (one time versus 20 times versus 10000 times)? Or does a decent compiler do the same thing as approach 1 anyway?

Upvotes: 3

Views: 92

Answers (2)

Bathsheba
Bathsheba

Reputation: 234815

Don't try to do the job of a modern compiler as they place a lot of emphasis on code optimisation: shy away from purported improvement tricks such as these.

Not only is it obfuscating but approach 1 is also vulnerable to an errant refactorer dropping the & in the definition of str: if that is ever done then the returned pointer will be dangling and the program behaviour undefined! It's for these reasons that I would disallow approach 1 in my codebase.

Upvotes: 4

Mohit Jain
Mohit Jain

Reputation: 30489

From 8.3.2 References §4

It is unspecified whether or not a reference requires storage

So I would suggest use the code that looks more readable to you and leave the rest to the compiler.

Upvotes: 3

Related Questions