【小白C++学习之路】C++常见错误总结

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