C++ pointer to objects

前端 未结 7 562
野趣味
野趣味 2020-12-07 16:19

In C++ do you always have initialize a pointer to an object with the new keyword?

Or can you just have this too:

MyClass *myclass;

mycl         


        
7条回答
  •  攒了一身酷
    2020-12-07 16:26

    No you can not do that, MyClass *myclass will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.

    In C++, you can create objects either on stack or heap like this:

    MyClass myClass;
    myClass.DoSomething();
    

    Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass variable goes out of scope.

    Other way of allocating memory is to do a new . In that case, you have to take care of releasing the memory by doing delete yourself.

    MyClass* p = new MyClass();
    p->DoSomething();
    delete p;
    

    Remeber the delete part, else there will be memory leak.

    I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.

提交回复
热议问题