the arrow '->' separator is crashing when calling function from class

前端 未结 3 794
名媛妹妹
名媛妹妹 2021-01-29 05:46

I\'m working on a project for class and I\'m using classes and pointers of type class to call some functions in the class but it\'s crashing on Code Blocks and Eclipse and I don

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 06:06

    Basic rule: creating a pointer (a variable that contains the address of an object, or otherwise is NULL (or nullptr since 2011)) as pointed out by Christian Hackl in comments) does not create a corresponding pointee (an object who's address can be stored in the pointer).

    More formally, Ptr is an uninitialised pointer. Even accessing its value gives undefined behaviour (e.g. some_other_pointer = Ptr). For operator -> to work correctly, the pointer must first be initialised so it points at a valid object.

     a aobj;
     a *Ptr = &aobj;
     Ptr->set_X(42);   // OK
    
     a *Ptr2 = new a;
     Ptr2->set_X(42);    // OK
     delete Ptr2;
    

提交回复
热议问题