代码在Visual Studio 2010中编译,但不应该编译 [英] Code compiles in Visual Studio 2010 but shouldn't compile at all

查看:159
本文介绍了代码在Visual Studio 2010中编译,但不应该编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下源代码使用Visual Studio 2010正确编译:

 命名空间NS 
{
X
{
};
X Y(X str);
}

void myFun()
{
NS :: X x;
Y(x);
}

(这是缩减的代码,其中所有我自己的类和函数名称已被替换X,Y,...)



我希望行 Y(x)编译,因为它应该是 NS :: Y(x)



命令

  cl / c file.cpp 

这里没有其他文件,没有其他命令行选项。



为什么这个文件编译?
在VS2010中的错误?

解决方案

你遇到的是由于 ADL 参数依赖查找)。



您的代码段没有问题(除了链接器可能会抱怨 NS :: Y 未定义的事实),但它应该编译 - VS2012正在处理片段,因为它应该。



编译器会找到 NS :: Y 因为参数 x NS :: X )的类型在适当的范围内。







3.4.2 查找 当使用非限定名称时, 函数调用(5.2.2)中的后缀表达式,可以搜索在
通常的未限定查找(3.4.1)期间未考虑的其他命名空间,并且在那些
命名空间中,命名空间范围的朋友函数声明(11.4)不是
否则可见。



这些对搜索的修改取决于
的类型


  • 对于函数调用中的每个参数类型T,都有一个参数一组零个或多个关联的命名空间以及一组零个或多个
    相关联的类。



    命名空间和
    类的集合完全由函数参数
    (和任何模板模板参数的命名空间)的类型决定。




  • The following source code compiles correctly with Visual Studio 2010:

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

    (this is reduced code where all my own class and function names have been replaced by X, Y, ...)

    I would expect that the line Y(x) would fail 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 included here, no other command line options.

    Why does this file compile? Bug in VS2010? Or something that I (and my 3 other colleagues) overlooked?

    解决方案

    What you are experiencing is due to ADL (Argument Dependent Lookup).

    There is nothing wrong with your snippet (besides the fact that the linker will probably complain about NS::Y isn't defined), but it should compile - VS2012 is handling the snippet as it should.

    The compiler will find NS::Y due to the fact that the type of parameter x (NS::X) is in the appropriate scope.


    3.4.2 Argument-dependent name lookup [basic.lookup.argdep]

    1. When an unqualified name is used as the postfix-expression in a function call (5.2.2), other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and in those namespaces, namespace-scope friend function declarations (11.4) not otherwise visible may be found.

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

    2. For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered.

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

    这篇关于代码在Visual Studio 2010中编译,但不应该编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆