
----- "Artyom" <artyomtnk@yahoo.com> a écrit :
From: Dean Michael Berris <mikhailberis@gmail.com>
On Sat, Jan 29, 2011 at 11:25 PM, Artyom <artyomtnk@yahoo.com> wrote:
From: Dean Michael Berris <mikhailberis@gmail.com> On Sat, Jan 29, 2011 at 8:06 PM, Artyom <artyomtnk@yahoo.com> wrote:
No, it's not obvious. Here's why:
fd = creat(file.c_str(), 0666);
What does c_str() here imply? It implies that there's a buffer somewhere that is a `char const *` which is either created and returned and then held internally by whatever 'file' is.
It implies that const file owns const buffer that holds null terminated string that can be passed to "char const *" API.
Yes, which is the problem in the first place. Every instance of string would then need to have that same buffer even if that string is just a temporary or worse just a copy.
It would not happen if it holds the data as linear single chunk :-)
Now let's say what if file changed in a different thread, what happens to the buffer pointed to by the pointer returned by c_str()? Explain to me that because *it is possible and it can happen in real code*.
I'm sorry but string as anything else has value semantics that is:
- safe for "const" access from multiple threads - safe for mutable access from single thread
I don't see why string should be different from any other value type like "int" because following
x+=y + y
is not safe for integer as well.
The code I had shown is **perfectly** safe with string has has value semantics (which std::string has)
Now the point I was making was, in the case of a string that is immutable, you don't worry about the string changing *ever*, don't need a contiguous buffer for something that isn't explicitly required. It's value semantics *plus* immutability.
So you either should forbid
your_string const &operator=(your_string const &)
Which makes it even more useless (IMHO)
Or your statement is wrong because assignment can happen for example from other thread like
str = str + " suffux"
And this would change the string in run time.
Think str as a shared_ptr<const string_beast> with wrappers. This line does not mutate the structure previously pointed to, just like assigning a shared_ptr does not mutate the object previously pointed to. It makes str points to a newly created chain, which here happens to share data with the original chain but that's another story. Of course, this suppose that you got str by value. If you got it by non-const reference, you can have race issues with other threads, just like any assignment, regardless of the type. Ivan
participants (1)
-
Ivan Le Lann