Search code examples
c++11autotype-deduction

type deduction with auto &


Today I wrote some code dealing with binary tree. Later I noticed a bug in the code:

void find(TreeNode* root, int target) {
    stack<TreeNode*> myStack{{root}};
    while(!myStack.empty()){
        auto& top = myStack.top(); // here I used auto& by mistake
        ...
    }
}

However, I am confused with auto& top = myStack.top();. After the type deduction, what is the type for top? Is it TreeNode & or TreeNode* &?

How about if I used auto* top = myStack.top()?


Solution

    1. auto top = myStack.top(); will assign a local copy of myStack.top() to top.
      In this case the type of top will be TreeNode*.
    2. auto& top = myStack.top(); will assign a reference to myStack.top() to top.
      In this case the type of top will be TreeNode*&.
    3. auto* top = myStack.top() will assign myStack.top() to top.
      In this case the type of top will be TreeNode*.