Why is destructor hanging

后端 未结 2 1322
野趣味
野趣味 2021-01-24 02:47

Below code was working fine. However, when I enable p=&b in GetValue, the code failed \"Debug Assertion Failed\". Why?

class A{
int         


        
2条回答
  •  再見小時候
    2021-01-24 03:45

    To make a long story short, your code has undefined behaviour, so everything can happen. The undefined behaviour starts here:

    void A::GetValue(int b){
      *p=b;
      //p=&b;  this will cause destructor to hang, why?
    }
    

    p is nullptr when the function is called, so *p is undefined behaviour. The rest of your code doesn't even matter. And that's the end of the story.

    Sorry to be so blunt, but your use of pointers is so completely and utterly wrong that we cannot even know for sure what the intended behaviour of the code really is. Don't use pointers if you don't need to. Don't use dynamically allocated memory if you don't need to. If you need to, use std::vector, std::string, std::unique_ptr or other standard classes which hide the pointers from you, so that you don't have to write your own destructors. Avoid direct use of new and delete.

提交回复
热议问题