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

前端 未结 3 791
名媛妹妹
名媛妹妹 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:05

    a *Ptr;
    Ptr->set_X(5);
    

    Your Ptr does not point to anything. Trying to invoke a member function on an uninitialised pointer results in undefined behaviour. Crashing is just one of the many more or less random things that can happen.

    Luckily, in your example, you do not need a pointer anyway. You can simply write:

    a my_a;
    my_a.set_X(5);
    

    Pointers often point to dynamically allocated objects. If this is what you want, you must use new and delete accordingly:

    a *Ptr = new a;
    Ptr->set_X(5);
    delete Ptr;
    

    In modern C++, std::unique_ptr is typically a superior alternative because you don't have to manually release the allocated memory, which removes a lot of potential programming errors:

    auto Ptr = std::make_unique();
    Ptr->set_X(5);
    // no delete necessary
    

提交回复
热议问题