Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c++ - Difference between MoveInsertable and CopyInsertable?

Can someone provide a more lucid explanation of these two terms?

In other words, some simple explanation with an example, please.

(from : cppreference.com)

MoveInsertable : Specifies that a rvalue of the type can be copied in uninitialized storage.

CopyInsertable : Specifies that an instance of the type can be copy-constructed in-place, in uninitialized storage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These requirements are a relationship between a type T and a container X. A container has an allocator type, A, which it uses to allocate the memory for its contained objects.

If m is one of these allocators, p a T*, rv an rvalue of type T, and v an expression of type T:

  1. CopyInsertable is defined by the standard with:

    T is CopyInsertable into X means that the following expression is well-formed:

    allocator_traits<A>::construct(m, p, v);
    
  2. MoveInsertable is defined by the standard with:

    T is MoveInsertable into X means that the following expression is well-formed:

    allocator_traits<A>::construct(m, p, rv);
    

Now to understand these definitions, we must know what allocator_traits<A>::construct does. Quite simply, in this case it calls:

m.construct(p, v) // CopyInsertable case
m.construct(p, rv) // MoveInsertable case

v and rv still have their respective value categories here because std::forward is applied to the argument of allocator_traits<A>::construct.

So what does an allocators construct member function do? Well, as you might expect, it constructs an object of type T at the location p by doing:

::new ((void*)p) T(v) // CopyInsertable case
::new ((void*)p) T(rv) // MoveInsertable case

Again, v and rv are std::forwarded.

Of course, these will invoke the copy or move constructors respectively.

So:

  1. T is CopyInsertable into X: the allocator for X can placement-new construct an element of T, passing an expression of type T
  2. T is MoveInsertable into X: the allocator for X can placement-new construct an element of T, passing an rvalue of type T

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...