-1

If it does refcounting then is there a chance of Invalid memory access in pass by value case as there is single copy of string in memory?

rokumar
  • 11
  • 1
  • 1
    The standard doesn't say anything how `std::string` is implemented, it's left to the implementation. All the standard cares about is the interface and the behavior. – Some programmer dude Feb 19 '15 at 04:25
  • Also its a template class. You have the source for your implementation. Go see what it does. Note if you're implementation is C++11 compliant, then cow is [not really an option](http://stackoverflow.com/questions/16092143/shared-memory-and-copy-on-write-or-rvalue-references-and-move-semantics/16093748#16093748). – WhozCraig Feb 19 '15 at 04:26

1 Answers1

-1

Most string implementations do something called copy-on-write, which means that simply copying a string by value (through a copy constructor or operator= or whatnot) doesn't allocate new memory and doesn't copy the string contents. It's only if you write to this shared buffer that it does the copy, decrementing the reference counter to let the last string alive write to its own buffer safely.

This is all transparent though, you shouldn't care about how it works besides the academic value.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • I did indeed mean `gcc`'s implementation, though I always thought `cl` did it too. Live and learn! – Blindy Feb 19 '15 at 04:33