编译器默默接受从String类到const char *的错误自动转换

时间:2016-09-27 06:20:38

标签: c++ gcc compiler-errors

有这个问题。在我看来编译器工作得很糟糕,如果在代码中显示的情况3默默地接受从类String转换为const char *

我认为应该显示编译时错误。我错过了什么或者这真的是一个GCC编译器错误?

编译器是GCC(TDM-1)4.9.2

示例代码main.cpp使用命令行编译:g ++ main.cpp

main.cpp中:

#include <string>
#include <stdio.h>

class LogBlock {
public:
    explicit LogBlock( const char* info )
    :   m_info( info )
    {
        printf( "%s {\n", info );
    }

    ~LogBlock()
    {
        printf( "} %s done\n", m_info.c_str() );
    }

private:
    std::string m_info;
};


class String {
public:
    explicit String( const char* s ) : m_str( s ) {}

    const char* m_str;
};


int main()
{
    const char* bufInfo = "main";

    //// case 1) This behaves as expected - compiles and executes without problem:
    //LogBlock dummy_name1( "main" );

    //// case 2) This behaves as expected - compiler shows:
    //// "error: no matching function for call to 'LogBlock::LogBlock(String)"
    //LogBlock dummy_name2( String( "main" ) );

    // case 3) This does not behave as expected - compiles without any error message and works incorectly.
    // I think compiler should show same arror as in case 2) Why it does not work that?
    LogBlock dummy_name3( String( bufInfo ) );

    printf( "main body\n" );

    return 0;
}

0 个答案:

没有答案