C memset似乎不会写入每个成员

问题描述:

我写了一个小坐标类来处理int和float坐标。

I wrote a small coordinate class to handle both int and float coordinates.

template <class T>
class vector2
{
public:
    vector2() { memset(this, 0, sizeof(this)); }
    T x;
    T y;
};

然后在main()中执行:

Then in main() I do:

vector2<int> v;

但是根据我的MSVC调试器,只有x值设置为0,y值不变。 Ive从来没有在模板类中使用sizeof(),这是什么导致麻烦?

But according to my MSVC debugger, only the x value is set to 0, the y value is untouched. Ive never used sizeof() in a template class before, could that be whats causing the trouble?

memset - 它从 this $指向的位置开始,将指针的大小(在我的x86英特尔机器上的4个字节) c $ c>。这是一个坏习惯:当您使用复杂类使用 memset 时,您还将清除虚拟指针和指向虚拟基址的指针。而是做:

No don't use memset -- it zeroes out the size of a pointer (4 bytes on my x86 Intel machine) bytes starting at the location pointed by this. This is a bad habit: you will also zero out virtual pointers and pointers to virtual bases when using memset with a complex class. Instead do:

template <class T>
class vector2
{
public:
    // use initializer lists
    vector2() : x(0), y(0) {}
    T x;
    T y;
};