Mobile C ++ 0511 vector

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/baiyibin0530/article/details/90105331

Copy assignment

We can copy (initialization) objects through the constructor, but we can also copy vector by way of assignment.

The term & copies

<< arrow after the object is an input operator, it is to get the bulk of the side intake amount indicated by the arrows in the object, and returns the operation referred to

mobile

vector fill(istream& is)
{
    vector res;
    for(double x; is>>x;) res.push_back(x);
    return res;
}

void use()
{
    vector vec = fill(cin);
}

Vector class
{
    int SZ;
    Double elem *;
public:
    Vector (Vector && A); // constructor movement
    vector & operator = (vector &&) ; // move assignment
    // ..
}

Funny && symbol known as the "rvalue references." We use it to define the move operation. Note that, the moving operation is not connected
by the parameter const; i.e., we should use (vector &&) instead of (const vector &&).
One object of the move operation is to modify the source object, so that it becomes "empty." Define moving operation should be more simple than it should
be more efficient and simpler corresponding to the copy operation.

:: Vector Vector (Vector && a)
    : SZ a.sz {}, {elem} // a.elem a copy of elem and SZ
{
    a.sz = 0; // make a becomes empty Vector
    a.elem = nullptr a ;
}

vector & vector :: operator = (vector && a) // move to present to a Vector
{
    Delete [] elem; // release the old space
    elem = a.elem; // a copy of elem and SZ
    AZ = a.sz;
    a .elem = nullptr; // make a becomes empty Vector
    a.sz = 0;
    return the this *; // return a self-referential
}

Fill Vector (the istream & IS)
{
    Vector RES;
    for (Double X; X IS >>;) res.push_back (X);
    return RES;
}
move constructor function used to implement implicitly returned. The compiler knows to return a local value (RES) to leave
its scope, so it can be moved out of a value not copy it.

The importance of moving the constructor is that we do not have to return a large amount of information from the function pointer or reference processed.
Such defective following alternatives:
Vector * fill2 (the istream & IS)
{
   vecotor new new Vector * RES =;
    for (Double X; X IS >>;) RES-> push_back (X);
    return RES;
}

void use2()
{
    vector* vec = fill(cin);
    //...
}

When using this method, we must remember to release vector. Object on the release of free space is not as easy as it looks to achieve consistency and correctness.


 

Guess you like

Origin blog.csdn.net/baiyibin0530/article/details/90105331