Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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++.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading