Friday, 22 June 2018

Pointers, References, and Copy-on-Write


This implementation of copy-on-write allows us to preserve both efficiency and correctness — almost.

String s1 = "Hello";
char *p = &s1[1];
Our data structure at this point looks like this:


Now consider an additional statement: 
String s2 = s1;

The String copy constructor will make s2 share s1's StringValue, so the resulting data structure will be this one: 




The implications of a statement such as the following, then, are not pleasant to contemplate.
*p = 'x';                     // modifies both s1 and s2


===============================


a technique called copy-on-write (COW) is used. when a fork occurs, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the original copy of the page (which is now no longer shared). This technique is called copy-on-write.


std::string x("Hello");

std::string y = x;  // x and y use the same buffer

y += ", World!";    // now y uses a different buffer
                    // x still uses the same old buffer
 









No comments:

Post a Comment