Should C++ programmer avoid memset?

后端 未结 11 1379
遇见更好的自我
遇见更好的自我 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:38

    In C++ you should use new. In the case with simple arrays like in your example there is no real problem with using it. However, if you had an array of classes and used memset to initialize it, you woudn't be constructing the classes properly.

    Consider this:

    class A {
        int i;
    
        A() : i(5) {}
    }
    
    int main() {
        A a[10];
        memset (a, 0, 10 * sizeof (A));
    }
    

    The constructor for each of those elements will not be called, so the member variable i will not be set to 5. If you used new instead:

     A a = new A[10];
    

    than each element in the array will have its constructor called and i will be set to 5.

提交回复
热议问题