Some time ago I read an article that explained several pitfalls of argument dependent lookup, but I cannot find it anymore. It was about gaining access to things that you should not have access to or something like that. So I thought I’d ask here: what are the pitfalls of ADL?
Some time ago I read an article that explained several pitfalls of argument dependent
Share
There is a huge problem with argument-dependent lookup. Consider, for example, the following utility:
It’s simple enough, right? We can call
print_n()and pass it any object and it will callprintto print the objectntimes.Actually, it turns out that if we only look at this code, we have absolutely no idea what function will be called by
print_n. It might be theprintfunction template given here, but it might not be. Why? Argument-dependent lookup.As an example, let’s say you have written a class to represent a unicorn. For some reason, you’ve also defined a function named
print(what a coincidence!) that just causes the program to crash by writing to a dereferenced null pointer (who knows why you did this; that’s not important):Next, you write a little program that creates a unicorn and prints it four times:
You compile this program, run it, and… it crashes. “What?! No way,” you say: “I just called
print_n, which calls theprintfunction to print the unicorn four times!” Yes, that’s true, but it hasn’t called theprintfunction you expected it to call. It’s calledmy_stuff::print.Why is
my_stuff::printselected? During name lookup, the compiler sees that the argument to the call toprintis of typeunicorn, which is a class type that is declared in the namespacemy_stuff.Because of argument-dependent lookup, the compiler includes this namespace in its search for candidate functions named
print. It findsmy_stuff::print, which is then selected as the best viable candidate during overload resolution: no conversion is required to call either of the candidateprintfunctions and nontemplate functions are preferred to function templates, so the nontemplate functionmy_stuff::printis the best match.(If you don’t believe this, you can compile the code in this question as-is and see ADL in action.)
Yes, argument-dependent lookup is an important feature of C++. It is essentially required to achieve the desired behavior of some language features like overloaded operators (consider the streams library). That said, it’s also very, very flawed and can lead to really ugly problems. There have been several proposals to fix argument-dependent lookup, but none of them have been accepted by the C++ standards committee.