[C++ Error] invalid initialization of non-const reference of type 'std::__cxx11::string& {aka std::__cxx11::basi

1. Code

#include <string>
using namespace std;

void teststr(string& str)
{
        cout<<str<<endl;
}

void testint(int &a)
{
        cout<<a<<endl;
}

int main ()
{
        string str = "Hello World";
        teststr(str.substr(2));

        int a = 1, b=2;
        cout<<testint(a+b)<<endl;

        return 0;
}

2.make result

 

 3. Analysis and solution

Take (a + b) for example, the value of a + b will exist in a temporary variable. When passing this temporary variable to f, because the testint declaration, the parameter is int &, not a constant reference, because the c ++ compiler Of a semantic limitation. If a parameter is passed in as a non-const reference, the C ++ compiler has reason to think that the programmer will modify the value in the function, and the modified reference will play a role after the function returns. But if you pass in a temporary variable as a non-const reference parameter, due to the special nature of the temporary variable, the programmer cannot operate the temporary variable, and the temporary variable may be released at any time, so generally speaking, modify a temporary variable It is meaningless. According to this, the C ++ compiler added the semantic restriction that temporary variables cannot be used as non-const references.

4. Summary

C ++ temporary variables cannot be used as non-const reference parameters

5. Plan

Solution: add a cosnt in front of the parameter or remove the reference symbol

Guess you like

Origin www.cnblogs.com/stonemjl/p/12704757.html