我用 g++ (Ubuntu 7.4.0-1ubuntu1~18.04) 和 (MinGW.org GCC-8.2.0-3) 测试了以下代码。 p>
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引用,但这是我第一次遇到这种情况,我还没有找到解释和解决方案。我的问题是:
- const 值val2、const 引用ref1 和func 参数的初始化有什么区别?
- 为什么常量引用 ref1 的初始化会触发上述错误?
- 为什么显式调用构造函数不会触发 ref2 的错误?
- 它是标准的还是与其他编译器有什么不同?
- ref1 有解决方案吗?
谢谢。
最佳答案
感谢您的评论。事实上,它看起来像一个 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]
关于c++ - 具有字符串文字构造函数的类不适用于 const 引用初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58117343/