Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
Fabian Avatar asked Feb 20 '26 15:02

Fabian


1 Answers

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.

like image 181
Bathsheba Avatar answered Feb 23 '26 04:02

Bathsheba