Throw and ternary operator in C++

后端 未结 4 1377
盖世英雄少女心
盖世英雄少女心 2020-12-03 22:19

The following code compiles with G++ 4.6.1, but not with Visual Studio 2008

return (m_something == 0) ? 
    throw std::logic_error(\"Something wrong happene         


        
4条回答
  •  無奈伤痛
    2020-12-03 22:48

    Comeau compiles it without errors (here's my minimal compilable test case):

    int main(void)
    {
        int x = 17;
        return x ? throw "Something wrong happened" : 5;
    }
    

    which is pretty good evidence that it's allowed by the standard. So is the fact that MSVC crashes, rather than failing cleanly with an error.

    Also, it appears to be fixed in VC++ 2010

    R:\>cl ternarythrowtest.cpp
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    ternarythrowtest.cpp
    Microsoft (R) Incremental Linker Version 10.00.40219.01
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:ternarythrowtest.exe
    ternarythrowtest.obj
    

    and x64 version:

    R:\>cl ternarythrowtest.cpp
    Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    ternarythrowtest.cpp
    Microsoft (R) Incremental Linker Version 10.00.40219.01
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:ternarythrowtest.exe
    ternarythrowtest.obj
    

    Upgrade your compiler if possible, this is far from the only bug fixed in 2010.

提交回复
热议问题