简体   繁体   中英

C++: Constant Reference Parameters

why do we use Constant Reference Parameters in this code

 
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

// Converts a hex number as a string to decimal
int hex2Dec(const string& hex);   // here why we use reference and const it seems we do not change hex in the function body

// Converts a hex character to a decimal value
int hexCharToDecimal(char ch);

int main()
{
  // Prompt the user to enter a hex number as a string
  cout << "Enter a hex number: ";
  string hex;
  cin >> hex;

  cout << "The decimal value for hex number " << hex
    << " is " <<  hex2Dec(hex) << endl;

  return 0;
}

int hex2Dec(const string& hex)
{
  int decimalValue = 0;
  for (unsigned i = 0; i < hex.size(); i++)
    decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);

  return decimalValue;
}

int hexCharToDecimal(char ch)
{
  ch = toupper(ch); // Change it to uppercase
  if (ch >= 'A' && ch <= 'F')
    return 10 + ch - 'A';
  else // ch is '0', '1', ..., or '9'
    return ch - '0';
}

what is the use of calling by reference in this problem?

in this segment of code

int hex2Dec(const string& hex)
{
  int decimalValue = 0;
  for (unsigned i = 0; i < hex.size(); i++)
    decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);

  return decimalValue;
}

we do not change the hex.

what is the purpose of const reference in this example and in genral?

The naive solution is to use int hex2Dec(string hex) here. However because function arguments are copied in C++ calling this function would cause a new string to be created for hex , copied from the function argument every time hex2Dec is called. This can lead to needless performance issues, specially if the strings are large.

The solution to this problem is to pass the argument by reference. Using int hex2Dec(string & hex) fixes the first problem, now calling the function never causes a new string to be created. It always refer to whatever string was given.

This introduces a new problem. First, because the argument is a reference, it's possible for the function to change the argument. Because we can see the function implementation, we know it doesn't. But anyone trying to use that function can't know that. Second, because of this, it is not possible to call the function with a const string . The compiler knows it is forbidden to change a const string and it sees that the function doesn't promise not to change it so it will produce an error if you try it. This is very limiting, for example it wouldn't be possible to call the function with a string literal (ex. hex2Dec("test") ).

#include <string>

int hex2Dec(std::string& hex);

int main()
{
    std::string foo = "foo";
    const std::string bar = "bar";
    
    hex2Dec(foo);       // Okay
    //hex2Dec(bar);     Compilation Error
    //hex2Dec("baz");   Compilation Error
}

The solution to this new problem is to add const to the argument type: int hex2Dec(const string & hex) . The const means that this reference can never be used to modify the argument. Now, users of the function and the compiler both know its safe to use the function with const string s, and the calling the function never copies the argument.

#include <string>

int hex2Dec(const std::string& hex);

int main()
{
    std::string foo = "foo";
    const std::string bar = "bar";
    
    hex2Dec(foo);       // Okay
    hex2Dec(bar);       // Okay
    hex2Dec("baz");     // Okay
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM