以下代码引出内存泄漏(使用xcode 7.0.1和mac os 10.11测试)。泄漏位于以下行:std::cout << m(0,0) << std::endl;
有人可以解释原因吗?当我删除此行时,泄漏消失。我想它与()运算符的重载有关,但我不知道我做错了什么。
Matrix.h:
template<typename T>
class Matrix {
public:
Matrix(unsigned int rows, unsigned int columns, T initValue)
: size_(rows*columns), columns_(columns), rows_(rows) {
data_ = new T[size_];
for (unsigned int i = 0; i < size_; ++i) {
data_[i] = initValue;
}
}
Matrix(unsigned int rows, unsigned int columns)
: columns_(columns), rows_(rows) {
data_ = new T[size_];
for (unsigned int i = 0; i < size_; ++i) {
data_[i] = 0;
}
}
~Matrix() {
delete [] data_;
}
T& operator()(const unsigned int &row, const unsigned int &column) {
assert(row < rows_ && column < columns_);
return data_[row * columns_ + column];
}
T operator()(const unsigned int &row, const unsigned int &column) const {
assert(row < rows_ && column < columns_);
return data_[row * columns_ + column];
}
private:
T *data_;
unsigned int size_, columns_, rows_;
};
MAIN.C:
int main(int argc, char** argv)
{
Matrix<double> m( 2,2, 1.0 );
std::cout << m(0,0) << std::endl;
}