我试图设置一个Matrix类,并且想知道复制构造函数。我已阅读copy-and-swap idiom和operator overloading。我无法确定哪个更有效:
解决方案1:
Matrix<T>::Matrix(const Matrix<T>& rhs) {
Matrix<T> temp(rhs);
this.swap(temp);
}
Matrix<T>::void swap(Matrix<T> rhs)
: dx(rhs.dx), dy(rhs.dy) {
allocArrays();
for (int i=0; i<dx; ++i) {
for (int j=0; j<dy; ++j) {
p[i][j] = rhs.p[i][j];
}
}
}
或采取简单的路线,只需使用
解决方案2:
Matrix::Matrix(const Matrix& rhs)
: dx(m.dx), dy(m.dy) {
allocArrays();
for (int i=0; i<dx; ++i) {
for (int j=0; j<dy; ++j) {
p[i][j] = rhs.p[i][j];
}
}
}
Matrix Header:
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
template <typename T> class Matrix {
private:
std::vector<std::vector<T>> matrix;
void allocArrays();
unsigned int dx, dy; // dimensions of x and y
long **p; // pointer to pointer for long int
public:
Matrix();
~Matrix();
Matrix(const Matrix<T>& rhs);
Matrix(unsigned xSize, unsigned ySize);
Matrix<T>& operator=(const Matrix<T>& rhs);
// Adding below code to showcase what else will be happening with the Matrices
// Matrix mathematical operations
Matrix<T> operator+(const Matrix<T>& rhs);
Matrix<T>& operator+=(const Matrix<T>& rhs);
Matrix<T> operator-(const Matrix<T>& rhs);
Matrix<T>& operator-=(const Matrix<T>& rhs);
Matrix<T> operator*(const Matrix<T>& rhs);
Matrix<T>& operator*=(const Matrix<T>& rhs);
Matrix<T> transpose();
// Matrix/scalar operations
Matrix<T> operator+(const T& rhs);
Matrix<T> operator-(const T& rhs);
Matrix<T> operator*(const T& rhs);
Matrix<T> operator/(const T& rhs);
// Matrix/vector operations
std::vector<T> operator*(const std::vector<T>& rhs);
std::vector<T> diag_vec();
// Access the individual elements
T& operator()(const unsigned& row, const unsigned& col);
const T& operator()(const unsigned& row, const unsigned& col) const;
};
#include "matrix.cpp"
#endif
Matrix CPP文件:
#ifndef _MATRIX_CPP
#define _MATRIX_CPP
#include "matrix.h"
#include <iostream>
// Default Constructor
Matrix<T>::Matrix() : Matrix(1, 1) {}
// Parameter Constructor
template<typename T>
Matrix<T>::Matrix(unsigned xSize, unsigned ySize)
: dx(xSize), dy(ySize) {
allocArrays();
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
p[i][j] = 0;
}
}
}
// Copy Constructor @ which is most effective way of doing this
template<typename T>
Matrix<T>::Matrix(const Matrix<T>& rhs) {}
Matrix<T>::void allocArrays() {
p = new long*[dx];
for (int i = 0; i < dx; i++)
p[i] = new long[dy];
}
答案 0 :(得分:2)
第一个解决方案意味着一个递归的构造函数调用,永远不会工作:
Matrix<T>::Matrix(const Matrix<T>& rhs) {
Matrix<T> temp(rhs);
^^^^^^^^^^^^^^
// Recursive call here
this.swap(temp);
}
对于任何潜在的性能差异,请始终在一组体面的测试用例上使用分析器。如果您的交换正确实现,您将看到任何体面的编译器,与分配/填充矩阵相比,交换临时的创建成本可以忽略不计。
注意:强>
如链接所示,复制和交换习惯用法由赋值运算符(调用复制构造函数)实现,而不是复制构造函数本身。