I was writing a parser where my code had a structure like this (removed all the non-important parts for this question):
class Token
{
private:
char kind;
public:
Token(char kind) : kind(kind) {}
inline char getKind() const {return kind;}
};
class Parser
{
private:
const std::vector<Token>& tokens;
public:
Parser(const std::vector<Token>& tokens) : tokens(tokens) {}
};
The &
after std::vector<Token>
was added by accident. The result was that the following returned a undefined value:
auto it = tokens.begin();
(*it).getKind();
After finding the problem I removed the &
and the code worked as intended. What I am wondering about is what const std::vector<Token>& tokens;
really does? The code did not give any compiler warning or error so does that mean that mean using &
like this is useful in some cases?
1