How can I prevent caller to my function from using the same pass-by-reference variable in C++?

  alias, c++, output-parameter, pass-by-reference

I have a legacy interface that has a function with a signature that looks like the following:

int provide_values(int &x, int &y)

x and y are considered output parameters in this function. Note: I’m aware of the drawbacks of using output parameters and that there are better design choices for such an interface. I’m not trying to debate the merits of this interface.

Within the implementation of this function, it first checks to see if the addresses of the two output parameters are the same, and returns an error code if they are.

if (&x == &y) {
    return -1;  // Error:  both output parameters are the same variable
}

Is there a way at compile time to prevent callers of this function from providing the same variable for the two output parameters without having such a check within the body of the function? I’m thinking of something similar to the restrict keyword in C, but that only is a signal to the compiler for optimization, and only provides a warning when compiling code that calls such a function with the same pointer.

Source: Windows Questions C++

LEAVE A COMMENT