1、臨時變量的非const引用
class Solution { public: void __dfs(vector<string> &paths, string &path, int loc, int n, int left, int right) { if (loc == 2*n){ paths.push_back(path); return; } if (left < n){ __dfs(paths, path+"(", loc+1, n, left+1, right); //path.pop_back(); } if (right < left){ __dfs(paths, path+")", loc+1, n, left, right+1); //path.pop_back(); } } vector<string> generateParenthesis(int n) { // 遞歸法來做 vector<string> paths; string s; __dfs(paths, s, 0, n, 0, 0); return paths; } };
編譯報錯:Line 11: Char 34: error: cannot bind non-const lvalue reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string<char>&'} to an rvalue of type 'std::__cxx11::basic_string<char>'
這個錯誤是C++編譯器的一個關於語義的限制。
如果一個參數是以非const引用傳入,c++編譯器就有理由認為程序員會在函數中修改這個值,並且這個被修改的引用在函數返回后要發揮作用。但如果你把一個臨時變量當作非const引用參數傳進來,由於臨時變量的特殊性,程序員並不能操作臨時變量,而且臨時變量隨時可能被釋放掉,所以,一般說來,修改一個臨時變量是毫無意義的,據此,c++編譯器加入了臨時變量不能作為非const引用的這個語義限制。
2、string對象的索引返回是char型
string s = "hello"; // s[1]返回類型是char