What does *& mean in a function parameter

前端 未结 5 1099
春和景丽
春和景丽 2020-12-03 14:43

If I have a function that takes int *&, what does it means? How can I pass just an int or a pointer int to that function?

function(int *&am         


        
5条回答
  •  忘掉有多难
    2020-12-03 15:20

    It's a reference to a pointer to an int. This means the function in question can modify the pointer as well as the int itself.

    You can just pass a pointer in, the one complication being that the pointer needs to be an l-value, not just an r-value, so for example

    int myint;
    function(&myint);
    

    alone isn't sufficient and neither would 0/NULL be allowable, Where as:

    int myint;
    int *myintptr = &myint;
    function(myintptr);
    

    would be acceptable. When the function returns it's quite possible that myintptr would no longer point to what it was initially pointing to.

    int *myintptr = NULL;
    function(myintptr);
    

    might also make sense if the function was expecting to allocate the memory when given a NULL pointer. Check the documentation provided with the function (or read the source!) to see how the pointer is expected to be used.

提交回复
热议问题