C++ pointer to objects

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

    No, you can have pointers to stack allocated objects:

    MyClass *myclass;
    MyClass c;
    myclass = & c;
    myclass->DoSomething();
    

    This is of course common when using pointers as function parameters:

    void f( MyClass * p ) {
        p->DoSomething();
    }
    
    int main() {
        MyClass c;
        f( & c );
    }
    

    One way or another though, the pointer must always be initialised. Your code:

    MyClass *myclass;
    myclass->DoSomething();
    

    leads to that dreaded condition, undefined behaviour.

    0 讨论(0)
提交回复
热议问题