简体   繁体   中英

Move assignment on containers: state of previously contained objects

Coming from another question (actually, rather this one , but the former one is better reference), I could not find appropriate reference in the standard, apart from 20.5.5.15:

Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

Are there any requirements to the elements previously contained in the destination container, eg being destroyed before the assignment?

Example:

std::list<SomeClass> v1({10, 12});
std::list<SomeClass> v2({7});
v1 = std::move(v2);
for(auto sc : v2)
{
    std::cout << sc << ' ';
}

While GCC did not output anything at all ( std::vector and std::list alike), would be receiving 10 12 as output legal (appropriate operator<< provided) (eg received by just swapping the contents, especially not deleting the objects previously contained)?

As of now, I'd say "yes", but don't feel sure enough to rely on and too curious not to post a question...

If legal, would it come unexpected for any developers if elements are not destroyed immediately (eg in consequence some resources still held open while developer expects them to get closed)?

In [container.requirements.general] , we see

All existing elements of a are either move assigned to or destroyed. Ensures : a shall be equal to the value that rv had before this assignment.

Where a is the destination and rv is an rvalue. This could be achieved by swapping 1 with elements of the source destination, but most likely is done by resizing then moving.

  1. It would have to be through a non-specialisable __swap , to ensure the move assignments do occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM