0

Copy-on-Write | Example

Hi Refer code below: https://code.sololearn.com/cRlz0Kh7KmpM I am just copying a to b and still it allocates memory on heap. Is COW means I should not see allocation on heap for b string until I do not modify it. Is it right? But Since C++ string does not support COW, it allocates memory up front only. Can i see COW behavior on any of the default C++ or I have to implement only ? Thanks in advance..!

11th Apr 2022, 8:02 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
8 Antworten
+ 1
Certainly! In the context of COW (Copy-On-Write): Uniqueness refers to whether multiple strings share the same data initially. It's necessary because data is copied only when one of the copies is modified. Initially, copies share the same data, saving memory and time. The modify function checks if a string is unique; if not, it makes a copy to maintain data consistency during modification.
1st Oct 2023, 9:18 AM
D1M3
D1M3 - avatar
+ 1
Got it now. Thanks. Currently, one copy happens when b.modify and a.modify both are called. If i remove this uniq condition , two allocation happens if b.modify and a.modify both are called.
1st Oct 2023, 9:27 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
One last question . Sorry for too many questions. I never used unique as it seems new introduction in latest version. Does this be replaced with use_count usecase ? If use_count is more than 1 , then unique is false otherwise true.
1st Oct 2023, 9:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
So, yes, you can use use_count() to determine if a std::shared_ptr behaves like a std::unique_ptr.
1st Oct 2023, 9:43 AM
D1M3
D1M3 - avatar
0
Could you please elaborate what is meant by below line ? (!data.unique()) Thanks GamerGeil Hd
1st Oct 2023, 8:48 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
ItCreate a copy of the data if it's not unique
1st Oct 2023, 9:03 AM
D1M3
D1M3 - avatar
0
What uniquness it checks ? Content of string i.e. characters of string data we passed as argument ? Is it necessary ? This is done in modify function and it means we gonna modify a string so copy is necesary. Isn't it ? Or is it some case which I am missing and modify will prevent copy due to unique function ?
1st Oct 2023, 9:06 AM
Ketan Lalcheta
Ketan Lalcheta - avatar