当我在 Visual C++ 2012 中编写这个简单的代码时,我遇到了一个有趣的智能感知错误:类型的引用
"std::vector<Node*, std::allocator<Node*>> &" (non const-qualified)
不能用类型的值初始化
"std::vector<Node*, std::allocator<Node*>>".
但是我们可以成功构建代码而没有警告和错误。那么为什么 Visual C++ 2012 会报告这样一个智能感知错误呢?
#include <vector>
using std::vector;
class Node {
private:
vector<Node*> children;
public:
vector<Node*>& getChildren() {
return children;
}
void addChild(Node* child) {
children.push_back(child);
}
};
void f(Node* root)
{
vector<Node*>& tmp = root->getChildren(); // intellisense error on 'root' here
}
void main()
{
Node root;
Node child1, child2;
root.addChild(&child1);
root.addChild(&child2);
f(&root);
}