Does C ++ 11 semantics move overperfom copy-on-write idiom?

I may be confused, but I realized that:

  • COW will return a “fake” copy until one of the callers wants to make some changes.
  • Move Semantic will return a fake copy in all cases.

So, if my goal is to have an object that only needs to be read and not updated, should I just wait for the support of move semantics in my C ++ compilers?

I'm right?

Thanks:)

+4
source share
2 answers

Moving semantics does not return a “fake” copy. Instead, in a copy operation, it gives copy permission to delete the original copy.

A motivating example can be instructive:

std::vector<int> bigData; // fill bigData std::vector<std::vector<int> > listOfData; listOfData.push_back(std::move(bigData)); // after this point, the contents of bigData are unspecified (however accessing it is _not_ undefined behavior) 

Without move semantics, you need to copy bigData to paste it into listOfData or manually flip it with swap() into a new empty vector that is in listOfData. But with the move semantics, the aka move constructor std::vector constructor, called by push_back as it is copied to the new data, has permission to delete the old bigData content - this is allowed to steal the bigData internal pointer and reset bigData for an empty vector.

Movement semantics are usually faster than COW semantics, as they do not need to maintain reference counting for read-only shared data. They are, however, more limited - you cannot create multiple reference counts for your data using move semantics; you can easily and conveniently mix data between containers.

Also note that both the latest versions of GCC and Microsoft Visual C ++ support rvalue references and move semantics (GCC with --std=c++0x ), so there is no reason not to start using them today.

+6
source

copy-on-write and move constructors are two different things.

Let's talk about lines where COW implementations are common. Say you have a string implementation that supports COW and moves semantics. Consider this code:

 cow::string foo() { return string("foo"); } // move CTOR is in effect here. cow::string a = foo(); // move ctor in effect cow::string b = a; // copy ctor in effect 

a and b , the same selected sequence of characters will be shared here. Although here

 std::string foo() { return string("foo"); } // move CTOR is in effect here. std::string a = foo(); // move ctor in effect std::string b = a; // copy ctor in effect 

a and b will allocate and hold two different character sequences that double memory consumption.

0
source

Source: https://habr.com/ru/post/1385276/


All Articles