首页 > 解决方案 > 具有字符串文字构造函数的类不适用于 const 引用初始化

问题描述

我用 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. const value val2, const reference ref1func参数的初始化有什么区别?
  2. 为什么 const 引用ref1的初始化会触发上述错误?
  3. 为什么显式调用构造函数不会触发ref2的错误?
  4. 它是标准的还是与其他编译器有什么区别?
  5. ref1有解决方案吗?

谢谢你。

标签: c++

解决方案


谢谢您的意见。事实上,它看起来像一个 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]

推荐阅读