Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do stl containers use implicit sharing?

Tags:

c++

stl

Its known that Qt widgets use implicit sharing. So I am interested if stl containers std::vector, std::string use implicit sharing too.

If no, why? Since it is very useful.

And if the answer is yes, how we can ascertain in it? I need simple C++ stl program which shows that stl containers use implicit sharing. It doesn't do deep copy when is copied.

like image 368
Ashot Avatar asked Feb 05 '13 20:02

Ashot


2 Answers

As it's noticed in similar question:

The C++ standard doesn't prohibit or mandate copy-on-write or any other implementation details for std::string. So long as the semantics and complexity requirements are met an implementation may choose whatever implementation strategy it likes.

I think, same is true for std::vector

Also, you may be interested in this topic: How is std::string implemented

like image 123
Artem Sobolev Avatar answered Sep 29 '22 21:09

Artem Sobolev


No. They cannot. When you try to modify the contents of the container, or even calling a mutable begin() on it, it would imply a potential copy-on-write and thus invalidate all references and iterators to the container. This would be a hard to debug situation, and it is prohibited.

Although std::string is technically not a container, it is still prohibited to do copy-on-write since C++11:

References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_string object:
...
— Calling non-const member functions, except operator[], at, front, back, begin, rbegin, end, and rend.

[string.require]

... Since it is very useful.

Heh, what for? Passing by reference almost always solves all 'performance problems'. Atomic ref-counts are inherently non-scalable on multi-processors machines.

like image 21
Yakov Galka Avatar answered Sep 29 '22 23:09

Yakov Galka