[英]Strange bug C++ 11 template class
All compiles well.一切都编译得很好。 But the output contains a strange error I do not understand.
但是输出包含一个我不明白的奇怪错误。 Would be great if someone could help me with that.
如果有人可以帮助我,那就太好了。
main():主要的():
vector<PointGeneric<float>> v(3);
for (int i = 0; i < v.size(); i++)
{
v[i] = {(float)(i*1.1), (float)(i*0.9)};
cout << "1: v[" << i <<"] = " << v[i] << endl;
}
for (int i = 0; i < v.size(); i++)
cout << "2: v[" << i <<"] = " << v[i] << endl;
Output:输出:
1: v[0] = (0.000000, 0.000000)
1: v[1] = (1.100000, 0.900000)
1: v[2] = (2.200000, 1.800000)
2: v[2] = (2.200000, 1.800000)
2: v[2] = (2.200000, 1.800000)
2: v[2] = (2.200000, 1.800000)
Template Class: (not my own, taken from "svg-curve-lib" library on github and very slightly modified; in the original context all works well)模板类:(不是我自己的,取自 github 上的“svg-curve-lib”库并稍作修改;在原始上下文中一切正常)
template <typename Tx = float, typename Ty = Tx>
struct PointGeneric
{
public:
struct x_getter;
struct y_getter;
x_getter x{this};
y_getter y{this};
PointGeneric() : PointGeneric { 0, 0} {}
PointGeneric(Tx x, Ty y) : x(this), y(this), _x{x}, _y{y} {};
...
private:
Tx _x;
Ty _y;
};
x_getter - struct: x_getter - 结构:
template <typename Tx = float, typename Ty = Tx>
struct PointGeneric<Tx, Ty>::x_getter
{
public:
x_getter(PointGeneric *t): thisPointer{t} {};
operator Tx() const {return this->thisPointer->_x;};
private:
PointGeneric<Tx, Ty>* thisPointer;
};
At least in the code shown, PointGeneric
doesn't have a user-defined copy constructor or assignment operator, and neither does x_getter
.至少在显示的代码中,
PointGeneric
没有用户定义的复制构造函数或赋值运算符, x_getter
也没有。 Implicitly-defined versions would make it so that, after隐式定义的版本会使得,在
PointGeneric<float> source;
PointGeneric<float> dest = source;
you'll have dest.x.thisPointer
point to source
, not to dest
(and similarly for dest.y
; and mutatis mutandis for assignment).您将有
dest.x.thisPointer
指向source
,而不是dest
(对于dest.y
也是dest.y
;并且比对赋值)。
In your example, you have在你的例子中,你有
v[i] = {(float)(i*1.1), (float)(i*0.9)};
Here, source
is a temporary, destroyed at the semicolon, leaving v[i].x.thisPointer
a dangling pointer.这里,
source
是一个临时的,在分号处销毁,留下v[i].x.thisPointer
一个悬空指针。 I presume (though it's not shown) that the expression cout << v[i]
ends up calling v[i].x.operator float()
, which in turn attempts to deference thisPointer
, whereupon your program exhibits undefined behavior.我认为(虽然它没有显示)表达式
cout << v[i]
最终会调用v[i].x.operator float()
,它反过来试图尊重thisPointer
,因此你的程序表现出未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.