Search code examples
c++pointersiteratorpass-by-reference

C++ pass iterator vs. pointer to function


I'm writing a recursive function that loops over a list of lists. This is the header of the function:

void findDirToDelete(Directory*& current_dir_ptr, Directory*& dir_to_delete, int space_to_free) {

and this is the part of the function that is interesting in the context of this question:

Directory* ptr = nullptr;
for (auto it : current_dir_ptr->children) {
    ptr = ⁢
    findDirToDelete(ptr, dir_to_delete, space_to_free);
}

This code compiles, and runs. The class Directory contains, among other attributes, a list<Directory> children element.

My question is, why does that code above compile, but not the following?

for (auto it : current_dir_ptr->children) {
    findDirToDelete(&it, dir_to_delete, space_to_free);
}

This is the compile error that I get:

'void findDirToDelete(Directory *&,Directory *&,int)': cannot convert argument 1 from 'Directory *' to 'Directory *&'

I have a feeling it's because the function is taking the first element by reference, but I cannot really explain why (sort of beginner here...).

Thanks in advance!


Solution

  • Your function's parameter is a Directory *& which is a reference. It is a reference to a pointer, but that's a secondary detail, it is a reference before anything else.

    In C++ a reference cannot be bound to a prvalue. In less formal, slightly imprecise terms, you cannot pass most kinds of expressions as a reference parameter. That's just one of the rules of C++, there are no exceptions or workarounds.

    &it is an expression that produces a pointer. It cannot be bound to a reference.

    ptr is an lvalue, a named object. Creating a reference to a named object is allowed in C++.