1

I have a function that takes a CString as one of the parameters and I was looking through the code base and many places have const CString& instead as a argument.

So I want to know if there is a performance or behavior difference between using CString vs const CString&?

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
user163824
  • 115
  • 5

2 Answers2

1

Passing by value for a C++ non-trivial class involves invoking the copy constructor, so the decision, performance-wise, depends from what it does.

If we are talking about MFC/ATL CString, its copy constructor doesn't perform a deep copy like std::string (which may indeed be quite costly to copy, as, in the general case, it requires a new allocation and the copy of the full content), as it implements "copy on write" optimization - copies of a given CString actually share the backing buffer until one of them tries to modify it, thus triggering the actual copy. For this reason, copies are relatively cheap, but they still involve some atomic integer fiddling, which may be not completely free on modern processors.

So: most probably a const reference is going to be slightly faster to pass (even though access to actual data inside the function is going to suffer slightly due to an extra indirection step), but that's not anything I'd really worry about unless profiling does show it to be a bottleneck.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
-1

Usually no. A good compiler & optimizer should produce the same assembly.

This is because references are implemented as pointers in all of the major compilers and passing a trivial data type such as a char* via value or pointer makes no difference because at assembly level the passing of the argument to the function is both the same, sizeof(char*) == sizeof(char**).

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122