问题描述:

How would you define and declare a function that would just not accept any parameter that get passed by value, in C++.

Like the following should return an error:

#include <iostream>

using namespace std;

// function declaration

void swap(int &x, int &y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

swap(a, b); //This call MUST NOT be valid.

int &x = a;

int &y = b;

swap(x,y); // This one should be valid.

cout << "After swap, value of a :" << a << endl;

cout << "After swap, value of b :" << b << endl;

return 0;

}

void swap(int &x, int &y) {

int temp;

temp = x; /* save the value at address x */

x = y; /* put y into x */

y = temp; /* put x into y */

return;

}

in line swap(a, b) arguments are passed by value. I want it to return error when done like this.

Update

I was asked this question in an interview. To define a method which that returns an error when it gets called by values.

Like in above swap function call in main a and b must be references.

网友答案:

Let

int a{};
int& b{a};

then you cannot declare or define a function foo in a way that makes

foo(b);

compile while

foo(a);

does not compile/work.

If foo is declared like foo(int& c) then upon calling foo the compiler will bind the reference c to object a - no matter whether you passed a or b because the reference c can bind to any non-const, non-volatile lvalue of type int.

Within the scope of a and b both are lvalues an from the point of C++ there shouldn't be a difference in the call to foo because that's what references are about: They are just some kind of "named alias" to the original object.

Defining the function swap(int&, int&) already prevents "call by value". The term "call by value" vs. "call by reference" refers to a property of the function paramter not of the passed object.

网友答案:

Pass By Value : The local parameters are copies of the original arguments passed in Changes made in the function to these variables do not affect originals.

void swapByValue(int a, int b) {
    // Swap the value of a and b
}

Pass By Reference : The local parameters are references to the storage locations of the original arguments passed in. Changes to these variables in the function will affect the originals No copy is made, so overhead of copying (time, storage) is saved

void swapByReference(int& a, int& b) {
    // Swap the value of a and b
}

Please note that you call the both function in same manner. It's compiler which identifies the function definition and work accordingly.

void swapByReference(a,b); // This will modify the actual value of a and b
void swapByValue(a,b); // This will not modify the actual value of a and b
相关阅读:
Top