C memset似乎不会写入每个成员 [英] C memset seems to not write to every member

查看:175
本文介绍了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 。这是一个坏习惯:当您使用复杂类使用 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;
};

这篇关于C memset似乎不会写入每个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆