C ++:函数获取指针或引用

时间:2015-05-08 19:25:29

标签: c++ pointers reference

当函数获取指针或引用时,我有一些非常不清楚的事情。

让我们说实施BFS。这是我的实施:

// Assuming There is a class Node :
class Node {
    public:
    int val;
    bool visited;
    list<Node*> neighbours;
};

void BFS (Node* root) {
    if(root == NULL) {
        return ;
    }

    queue<Node*> Q;
    Q.push(root);

    while(!Q.empty()){
        Node* temp = Q.front();
        Q.pop();

    for(list<Node*>::iterator it = root->neighbours.begin() ; it != root->neighbours.end() ; it++){
            if((*it)->visited == true) continue;
            Q.push((*it));
            (*it)->visited = true;
        }

        if(!Q.empty()){
            cout << temp->val << ",";
        } else {
            cout << temp->val << endl;
        }
    }
}

我的问题是:函数BFS应该获取指针或引用吗?为什么?

另外,我很高兴听到关于其实施的更多评论。

非常感谢!

2 个答案:

答案 0 :(得分:1)

为什么将指针用作函数参数

可能有不同的方法和不同的原因
  1. 如果要在BFS函数中进行指针运算,则应使用指针作为参数。
  2. 有时检查指针是否为空并根据它执行某些操作非常有用。
  3. 看起来这可能不是使用指针作为参数的一个重要原因,但InsertOneAsync可以保存非常重要的信息。例如,存在二进制搜索树实现,其中null指针显示节点是叶子。

    在您的示例中,您还检查null是否为空,并返回该情况。

答案 1 :(得分:0)

我建议将其保持为接受指针,以便检查是否为null。

Ref vs pointer benefits for C++

接受指针具有以下行为,并允许NULL(0)值

int main() {
  ...
  { 
    Graph g;
    ...
    Node x(...);   //x is a reference to a Node on the stack
    g.BFS(&x);     //Notice the need to use '&' to convert to pointer
  }

  {
    Graph g;
    ...
    Node* x = Node(...);   //x is a ("Node") pointer to a Node on the stack
    g.BFS(x);              //passes as a pointer
  }

  { 
    Graph g;
    ...
    Node* x = NULL;
    g.BFS(x)          //works -- is allowed
  }

  {
    Graph g;
    ...
    Node* x = new Node(...);   //x is a ("Node") pointer to a Node on the heap
    g.BFS(x);                  //passes as a pointer
  }
}

作为引用接受具有以下行为,并且不允许NULL(0)值:

int main() {
  ...
  { 
    Graph g;
    ...
    Node x(...);   //x is a reference to a Node on the stack
    g.BFS(x);     //Pass by reference
  }

  {
    Graph g;
    ...
    Node* x = Node(...);   //x is a ("Node") pointer to a Node on the stack
    g.BFS(*x);              //Notice the need to dereference x to pass by reference
  }

  {
    Graph g;
    ...
    Node* x = new Node(...);   //x is a ("Node") pointer to a Node on the heap
    g.BFS(*x);                  //Notice the need to dereference x to pass by reference
  }

  { 
    Graph g;
    ...
    Node* x = NULL;
    g.BFS(x)   //does not work, can't pass 0 val to function expecting a reference      
  }
}