具有字符串文字构造函数的类不适用于const参考初始化

时间:2019-09-26 12:58:39

标签: c++

我用g ++ (Ubuntu 7.4.0-1ubuntu1〜18.04)(MinGW.org GCC-8.2.0-3)测试了以下代码。 >

struct test {
    template <unsigned long int N>
    test(const char(&)[N]){
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

void func(const test&){}

int main(){
    test val1 = "test";
    const test val2 = "test";
    /* const test &ref1 = "test"; */
    const test &ref2 = (test)"test";
    func("test");
}

带有 ref1 评论的输出:

g++ test.cpp -o test.exe && test.exe
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(const char (&)[N]) [with long unsigned int N = 5]

未注释 ref1 的输出:

g++ test.cpp -o test.exe && test.exe
test.cpp: In function 'int main()':
test.cpp:15:24: error: invalid initialization of reference of type 'const test&' from expression of type 'const char*'
     const test &ref1 = "test";
                        ^~~~~~

我以为我知道并掌握c ++中的const引用,但这是我第一次遇到这种情况,并且找不到解决方案。我的问题是:

  1. 初始化常量值 val2 ,常量引用 ref1 func 的参数有什么区别?
  2. 为什么初始化const引用 ref1 会触发上述错误?
  3. 为什么显式调用构造函数不会触发 ref2 的错误?
  4. 它是标准的还是与其他编译器有什么区别?
  5. 是否有 ref1 的解决方案?

谢谢。

1 个答案:

答案 0 :(得分:0)

谢谢您的评论。确实,它看起来像是GCC错误。

等待解决此问题,我终于找到以下变通办法以便与GCC进行编译。我添加了一个构造器重载,该重载也仅接受字符串文字,但带有警告。这样我就可以确定哪一行导致我的代码出现问题。

#include <iostream>

struct test {
    template <unsigned long int N>
    test(const char(&)[N]){
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

    //Compatibility with GCC
    [[gnu::deprecated("[WARNING] Don't use string literals on const reference !")]]
    test(char *&&ptr){
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

void func(const test&){}

int main(){
    test val1 = "test";
    const test val2 = "test";
    const test &ref1 = "test";
    const test &ref2 = (test)"test";
    func("test");
}

使用GCC输出:

g++ test.cpp -o test.exe && test.exe
test.cpp: In function 'int main()':
test.cpp:21:24: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
     const test &ref1 = "test";
                        ^~~~~~
test.cpp:21:24: warning: 'test::test(char*&&)' is deprecated: [WARNING] Don't use string literals on const reference ! [-Wdeprecated-declarations]
test.cpp:11:5: note: declared here
     test(char *&&ptr){
     ^~~~
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(char*&&)
test::test(const char (&)[N]) [with long unsigned int N = 5]
test::test(const char (&)[N]) [with long unsigned int N = 5]

使用clang输出:

clang++ test.cpp -o test.out && ./test.out
test::test(const char (&)[N]) [N = 5]
test::test(const char (&)[N]) [N = 5]
test::test(const char (&)[N]) [N = 5]
test::test(const char (&)[N]) [N = 5]
test::test(const char (&)[N]) [N = 5]