Why don't I need to check if references are invalid/null?

前端 未结 11 2099
半阙折子戏
半阙折子戏 2020-12-23 11:20

Reading http://www.cprogramming.com/tutorial/references.html, it says:

In general, references should always be valid because you must always initi

11条回答
  •  一个人的身影
    2020-12-23 11:43

    Because by the time you reach there you have made an undefined behavior for sure. Let me explain :)

    Say you have:

    void fun(int& n);
    

    Now, if you pass something like:

    int* n = new int(5);
    fun(*n); // no problems until now!
    

    But if you do the following:

    int* n = new int(5);
    ...
    delete n;
    ...
    fun(*n); // passing a deleted memory!
    

    By the time you reach fun, you will be dereferencing *n which is undefined behavior if the pointer is deleted as in the example above. So, there is no way, and there must be now way actually because assuming valid parameters is the whole point of references.

提交回复
热议问题