【发布时间】:2021-02-08 15:04:35
【问题描述】:
我写了一个表达式模板代码,但出现了错误。
以下只是一个最小的可重现示例。
#include <iostream>
template<typename Derived>
class VecExp {
public:
double operator[](int i) const {return static_cast<Derived const&>(*this)[i];}
};
template<int n>
class Vector : public VecExp<Vector<n>> {
public:
template<int m>
Vector(const double(&arr)[m]) {
static_assert(m==n, "");
for(int i=0; i<m; ++i) data[i] = arr[i];
}
template<typename E>
Vector(const VecExp<E>& exp) {
for(int i=0; i<n; ++i) data[i] = exp[i];
}
double operator[](int i) const {std::cout<<this<<std::endl; return data[i];}
double& operator[](int i) {return data[i];}
double data[n];
};
template<typename E1, typename E2>
class VectorSum : public VecExp<VectorSum<E1, E2>>{
E1 const& lhs;
E2 const& rhs;
public:
VectorSum(E1 const& lhs, E2 const& rhs) : lhs(lhs), rhs(rhs) {
// std::cout << &(this->lhs) << ", " << &(this->rhs) << std::endl;
}
double operator[](int i) const {return lhs[i] + rhs[i];}
};
template<typename E1, typename E2>
VectorSum<E1, E2>
operator + (VecExp<E1> const& lhs, VecExp<E2> const& rhs) {
return VectorSum<E1, E2>(*static_cast<const E1*>(&lhs), *static_cast<const E2*>(&rhs));
}
int main() {
Vector<16> v({1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});
std::cout << &v << std::endl;
const auto sum = v + v + v + v;
Vector<16> v2 = sum; // error at here
std::cout << sum[0] << std::endl;
return 0;
}
当我尝试使用添加超过 3 个Vectors 的VectorSum<...>(sum in main())时,在发布版本中会出现以下错误。
Exception 0xc0000005 encountered at address 0x7ff76f8a1189: Access violation reading location 0x00000000
所以我像上面一样连接了指针打印机,然后它说
00000067C1EFF920
0000000000000000
Process finished with exit code -1073741819 (0xC0000005)
如果我附加更多打印机(即:在operator + 或VecSum ctor,...),那么突然一切正常。
谁能告诉我为什么会发生这个错误?
【问题讨论】: