更改此指针指向的值

时间:2014-10-28 22:59:47

标签: c++ pointers c++11 reference

我为我的矩阵结构编写了这段代码。它计算一个方形矩阵的值,该矩阵提升到e次幂,但这是无关紧要的。我想知道最后几行发生了什么。

是否将p的值复制到 this 指向的位置?它是浅拷贝还是深拷贝? 正在更改吗?我不这么认为,因为它是常量。

如何实施该副本以使其运行更快?

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;
}

2 个答案:

答案 0 :(得分:1)

如果您为班级添加了适当的缓冲区窃取支持,则以下其中一项会更快:

替换

*this = p;

由(C ++ 11中的首选)

*this = std::move(p);

或(对于C ++ 03,在C ++ 11中仍然可以正常工作)

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

但是,由于您无法在适当的位置覆盖左侧,因此最好是实施operator^,并按照以下方式编写operator^= < / p> <击>

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;
}

<击>

注意到你正在覆盖*this到位,连续的正方形。

答案 1 :(得分:0)

*this = p;调用你的矩阵的operator=(matrix)方法,如果它有一个,否则它调用编译器生成的operator=(),简单地执行成员的成员副本p的{​​{1}}字段中的this字段(使用各自的operator=()实现)。

相关问题