通过move赋值实现B=f(A)语法
Implementing the B=f(A) syntax by move assignment
我已经实现了一个矩阵类与移动赋值
template <typename OutType>
class Matrix
{
public:
int Rows_; // number of Rows
int Columns_; // number of Columns
OutType *data_; // row Major order allocation
// STUFF
Matrix<OutType> & operator=(Matrix<float>&& other) {
swap(other);
return *this;
}
void swap(Matrix<float>& other) {
int t_Rows_ = Rows_; Rows_ = other.Rows_; other.Rows_ = t_Rows_;
int t_Columns_ = Columns_; Columns_ = other.Columns_; other.Columns_ = t_Columns_;
float* t_ptr = data_;
data_ = other.data_;
other.data_ = t_ptr; }
}
来实现B=f(A);
语法,如
c++:实现B=f(A), B和A数组和B已经定义
作为可能的函数,我正在考虑FFT,实现为
Matrix<float> FFT(const Matrix<float> &in)
{
Matrix<float> out(in.GetRows(),in.GetColumns());
// STUFF
return out;
}
是否有进一步提高效率的空间?是否有进一步的技巧来改进,例如,移动分配或swap
函数?
编辑:KONRAD RUDOLPH注释后的新解
Matrix & operator=(Matrix&& other) {
std::swap(Rows_, other.Rows_);
std::swap(Columns_, other.Columns_);
std::swap(data_, other.data_);
std::cout << "move assigned n";
return *this;
}
我建议为您的类实现move-assignment和move-construction:
Matrix( Matrix<OutType> &&that ) noexcept
: Rows_(that.Rows_)
, Cols_(that.Cols_)
, data_(that.data_)
{
that.Rows_ = that.Cols_ = 0;
that.data_ = nullptr;
}
Matrix<OutType> &operator=( Matrix<OutType> &&that ) noexcept {
using std::swap;
swap( Rows_, that.Rows_ );
swap( Cols_, that.Cols_ );
swap( data_, that.data_ );
return *this;
}
如果你实现这样的移动操作(构造和赋值),std::swap
应该为你的代码工作得很好,你不需要提供你自己的。如果您确实想提供自己的swap
实现,我建议将其作为两个参数的friend
函数提供,以便可以通过参数依赖查找找到它。我还建议调用swap
(和所有其他函数)时不考虑名称空间限制,如上所示,这样ADL就不会被抑制(除非,由于某种原因,您确实需要指定调用哪个函数,并且为特定类型定制的重载是错误的)。在处理模板化代码时,ADL特别有价值。如果使用std::
限定符调用std::swap
,就会大大减少用户定义类型提供更有效交换实现的机会。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- 单独定义模板化嵌套类方法的正确语法
- 返回一个带有 std::move 的对象并链接函数
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 通过move赋值实现B=f(A)语法
- 在c++ 11移动构造函数中使用std::move,具有统一的初始化语法