简体   繁体   中英

Change value pointed by this pointer

I wrote this working piece of code for my matrix struct. It computes the value of a square matrix raised to the e-th power, but this is irrelevant. I want to know what is happening in the last lines.

Is the value of p being copied to the location pointed by this ? Is it a shallow copy or a deep copy? Is this being changed? I don't think so because it's const.

How can I implement that copy to make it run faster?

matrix& operator ^=(int e)
{
    matrix& b = *this;
    matrix p = identity(order());
    while (e) {
        if (e & 1)
            p *= b;
        e >>= 1;
        b *= b;
    }
    *this = p;
    return *this;
}

One of the following will make it faster, if you're added appropriate buffer-stealing support to your class:

Replace

*this = p;

by either (preferred in C++11)

*this = std::move(p);

or (for C++03, should still work ok in C++11)

swap(p); // if swap is a member
swap(*this, p); // if it's not

However, since you can't overwrite the left hand side in place, best is to implement operator^ , and write operator^= in terms of that:

 
 
 
  
  matrix operator^(const matrix& b, int e) { matrix p = identity(b.order()); // move or elision activated automatically while (e) { if (e & 1) p *= b; e >>= 1; b *= b; } return p; // move or NRVO activated automatically } matrix& operator^=(int e) { *this = (*this) ^ e; // move activated automatically since RHS is temporary // ((*this) ^ e).swap(*this); in C++03 return *this; }
 
  

Just noticed you are overwriting *this in place, with successive squares.

*this = p; invokes your matrix's operator=(matrix) method, if it has one, otherwise it invokes a compiler-generated operator=() that simple performs a member-by-member copy of p 's fields into this 's fields (using their respective operator=() implementations).

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