Compiling code in Visual Studio 2010, but should not compile at all

The following source code compiles correctly with Visual Studio 2010:

namespace NS { class X { }; XY(X str); } void myFun() { NS::X x; Y(x); } 

(this is abbreviated code, where all my own class and function names are replaced by X, Y, ...)

I would expect the string Y(x) not to compile, since it should be NS::Y(x) .

This source code is compiled with the following command

 cl /c file.cpp 

There are no other files, there are no other command line options.

Why is this file compiling? Error in VS2010? Or something that I (and my 3 other colleagues) did not notice?

+5
c ++ compiler-errors
source share
2 answers

What you are experiencing is related to ADL ( argument dependent ).

There is nothing wrong with your fragment (besides the fact that the linker is likely to complain about NS::Y , it is not defined), but it must compile - VS2012 processes the fragment as it should.

The compiler will find NS::Y because the parameter type x ( NS::X ) is in the corresponding region.


3.4.2 Search for argument-dependent names [ basic.lookup.argdep ]

  • When an unqualified name is used as a postfix expression in a function call (5.2.2), other namespaces that are not taken into account can be searched for a regular unqualified search (3.4.1), and in those namespaces, declarations of the namespace name function (11.4) and not otherwise visible can be found.

    These changes to the search depend on the types of arguments (and for template template arguments, the namespace is the template argument).

  • For each type of argument T, in a function call, there is a set of zero or more related namespaces and a set of zero or more related classes.

    The sets of namespaces and classes are completely determined by the types of function arguments (and the namespace of any template template argument).

+9
source share

This is valid C ++ code. It is compiled with search argument dependent here.

+3
source share

All Articles