Should C++ programmer avoid memset?

后端 未结 11 1380
遇见更好的自我
遇见更好的自我 2020-12-02 20:17

I heard a saying that c++ programmers should avoid memset,

class ArrInit {
    //! int a[1024] = { 0 };
    int a[1024];
public:
    ArrInit() {  memset(a, 0         


        
11条回答
  •  时光取名叫无心
    2020-12-02 20:42

    This is an OLD thread, but here's an interesting twist:

    class myclass
    {
      virtual void somefunc();
    };
    
    myclass onemyclass;
    
    memset(&onemyclass,0,sizeof(myclass));
    

    works PERFECTLY well!

    However,

    myclass *myptr;
    
    myptr=&onemyclass;
    
    memset(myptr,0,sizeof(myclass));
    

    indeed sets the virtuals (i.e somefunc() above) to NULL.

    Given that memset is drastically faster than setting to 0 each and every member in a large class, I've been doing the first memset above for ages and never had a problem.

    So the really interesting question is how come it works? I suppose that the compiler actually starts to set the zero's BEYOND the virtual table... any idea?

提交回复
热议问题