更改此指针指向的值
Change value pointed by this pointer
本文关键字:指针 更新时间:2023-10-16
我为我的矩阵结构编写了这段代码。它计算提高到 e 次方的方阵的值,但这无关紧要。我想知道最后几行发生了什么。
p 的值是否被复制到此指向的位置?是浅拷贝还是深拷贝?这是否正在改变?我不这么认为,因为它是常量。
如何实现该副本以使其运行得更快?
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;
}
如果向类添加了适当的缓冲区窃取支持,则以下方法之一将使其更快:
取代
*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^=
:
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
。
*this = p;
调用矩阵的operator=(matrix)
方法(如果有的话(,否则它会调用编译器生成的operator=()
,该简单地将p
的字段逐个成员复制到this
的字段中(使用它们各自的operator=()
实现(。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错