2009-12-28 17:56:23 +01:00
|
|
|
A tt(unique_ptr) hi(unique_ptr: move constructor) may be initialized
|
|
|
|
using an rvalue reference to a tt(unique_ptr) object for the same type:
|
2009-07-08 13:43:28 +02:00
|
|
|
verb(
|
|
|
|
unique_ptr<type> identifier(other unique_ptr object);
|
|
|
|
)
|
2009-12-27 14:53:38 +01:00
|
|
|
The move constructor is used, e.g., in the following example:
|
2009-07-08 13:43:28 +02:00
|
|
|
verb(
|
2009-12-27 14:53:38 +01:00
|
|
|
void mover(unique_ptr<string> &¶m)
|
|
|
|
{
|
|
|
|
unique_ptr<string> tmp(move(param));
|
|
|
|
}
|
2009-07-08 13:43:28 +02:00
|
|
|
)
|
|
|
|
Analogously, the assignment operator can hi(unique_ptr: assignment) be
|
2009-12-27 14:53:38 +01:00
|
|
|
used. A tt(unique_ptr) object may be assigned to a temporary tt(unique_ptr)
|
|
|
|
object of the same type (again move-semantics is used). For example:
|
2014-09-23 22:09:37 +02:00
|
|
|
verbinclude(-a examples/uniqueother.cc)
|
2009-12-27 14:53:38 +01:00
|
|
|
The example illustrates that
|
2009-07-08 13:43:28 +02:00
|
|
|
itemization(
|
2009-12-27 14:53:38 +01:00
|
|
|
it() tt(hello1) is initialized by a pointer to a dynamically alloctated
|
|
|
|
tt(string) (see the next section).
|
|
|
|
it() The tt(unique_ptr hello2) grabs the pointer controlled by tt(hello1)
|
|
|
|
using a move constructor. This effectively changes tt(hello1) into a
|
|
|
|
0-pointer.
|
|
|
|
it() Then tt(hello3) is defined as a default tt(unique_ptr<string>). But
|
|
|
|
then it grabs its value using move-assignment from tt(hello2) (which, as a
|
2010-10-11 16:47:42 +02:00
|
|
|
consequence, is changed into a 0-pointer as well)
|
2009-07-08 13:43:28 +02:00
|
|
|
)
|
2010-10-11 16:47:42 +02:00
|
|
|
If tt(hello1) or tt(hello2) had been inserted into tt(cout) a
|
2009-12-27 14:53:38 +01:00
|
|
|
emi(segmentation fault) would have resulted. The reason for this should now be
|
|
|
|
clear: it is caused by dereferencing 0-pointers. In the end, only tt(hello3)
|
|
|
|
actually points to the originally allocated tt(string).
|