C++ pointer to objects

前端 未结 7 587
野趣味
野趣味 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:28

    First I need to say that your code,

    MyClass *myclass;
    myclass->DoSomething();
    

    will cause an undefined behavior. Because the pointer "myclass" isn't pointing to any "MyClass" type objects.

    Here I have three suggestions for you:-

    option 1:- You can simply declare and use a MyClass type object on the stack as below.

    MyClass myclass; //allocates memory for the object "myclass", on the stack.
    myclass.DoSomething();
    

    option 2:- By using the new operator.

    MyClass *myclass = new MyClass();
    

    Three things will hapen here.

    i) Allocates memory for the "MyClass" type object on the heap.

    ii) Allocates memory for the "MyClass" type pointer "myclass" on the stack.

    iii) pointer "myclass" points to the memory address of "MyClass" type object on the heap

    Now you can use the pointer to access member functions of the object after dereferencing the pointer by "->"

    myclass->DoSomething();
    

    But you should free the memory allocated to "MyClass" type object on the heap, before returning from the scope unless you want it to exists. Otherwise it will cause a memory leak!

    delete myclass; // free the memory pointed by the pointer "myclass"
    

    option 3:- you can also do as below.

    MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
    MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
    myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.
    

    Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope.

    So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.

提交回复
热议问题