1. 程式人生 > 實用技巧 >cannot bind non-const lvalue reference of type 'std::__cxx11::string&

cannot bind non-const lvalue reference of type 'std::__cxx11::string&

1.問題

類的建構函式定義為:

Quote(std::string & s,double p):bookNo(s),price(p){}

如果這樣初始化物件:

Quote q("123",10);

就會報錯誤:

cannot bind non-const lvalue reference of type 'std::__cxx11::string&

而如果建構函式中的string添加了const,就不會報錯了。

2.解答

https://stackoverflow.com/questions/18565167/non-const-lvalue-references,講的很明白

因為一個臨時變數不能繫結到非const引用上。

上面的例子中“123”就建立了一個臨時string變數。

但是這個也和編譯器的版本有關,在VS中由於預設啟用了編譯器擴充套件,因此它可以正常工作。但是在GCC中會報錯。

https://blog.csdn.net/lisemi/article/details/103928596,這個說明了為什麼臨時變數不能繫結到非const引用上

https://www.cnblogs.com/area-h-p/p/11498481.html

如果一個引數是以非const引用傳入,c++編譯器就有理由認為程式設計師會在函式中修改這個值,並且這個被修改的引用在函式返回後要發揮作用。但如果你把一個臨時變數當作非const引用引數傳進來,由於臨時變數的特殊性,程式設計師並不能操作臨時變數,而且臨時變數隨時可能被釋放掉

,所以,一般說來,修改一個臨時變數是毫無意義的,據此,c++編譯器加入了臨時變數不能作為非const引用的這個語義限制。

3.例子

std::string a[10]={
        "hello",
        "world",
        "shenzhen"
};
void print(std::string& str){
        std::cout << str << std::endl;
}
std::string get_string(int i){
        return a[i];
}
int main(){
        print(get_string(
1)); return 0; }

會報錯error: cannot bind non-const lvalue reference of type

因為get_string返回的是一個臨時變數,可以解決的辦法:

1.print引數加上cosnt

2.print引數去掉&

3.get_string返回一個變數進行定義,再傳入print中