Argument passing by reference to pointer problem

后端 未结 5 1179
你的背包
你的背包 2021-02-06 10:20

Every time I try to compile my code I get error:

cannot convert parameter 1 from \'int *\' to \'int *&\'

The test code looks like this:

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 10:43

    The problem is, int*&val can only be passed an lvalue, which the result of &myVal is not. By changing the signature to void set(int* const& val), it's telling the compiler you're not going to change the value of the pointer.

    However, you normally wouldn't do that, only because if you're not going to change the value of the pointer, then passing the pointer by value is the most straightforward way to pass the value. And if you are going to change the value of the pointer, then you need to create a temporary to receive the result.

提交回复
热议问题