cppannotations/annotations/yo/stl/uniquemove.yo

31 lines
1.5 KiB
Text

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:
verb(
unique_ptr<type> identifier(other unique_ptr object);
)
The move constructor is used, e.g., in the following example:
verb(
void mover(unique_ptr<string> &&param)
{
unique_ptr<string> tmp(move(param));
}
)
Analogously, the assignment operator can hi(unique_ptr: assignment) be
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:
verbinclude(-a examples/uniqueother.cc)
The example illustrates that
itemization(
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
consequence, is changed into a 0-pointer as well)
)
If tt(hello1) or tt(hello2) had been inserted into tt(cout) a
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).