gpt4 book ai didi

c++ - 为什么 G++ 不为不返回任何内容的模板方法生成警告?

转载 作者:搜寻专家 更新时间:2023-10-31 00:00:30 24 4
gpt4 key购买 nike

考虑以下代码:

template <typename T>
class C2 {
public:
T method() { }
int method2() { }
};

g++ -Wall -c -pedantic 编译它给我以下警告:

test.cpp: In member function ‘int C2<T>::method2()’: test.cpp:4:29: warning: no return statement in function returning non-void [-Wreturn-type]

这是预期的。奇怪的是 method()也不返回任何东西。为什么不生成警告,因为实例化了 C2T = int使调用这两种方法同样危险?

最佳答案

如果你说 T = void , 然后没有 return需要声明。

仅仅因为您可以以一种损坏的方式使用您的模板并不意味着您必须这样做,并且编译器可能会给您带来怀疑的好处。

还要记住,类模板的成员函数仅在使用时实例化。所以真正导致错误的方法是C2<char> x; x.method(); ,这确实会产生警告。

关于c++ - 为什么 G++ 不为不返回任何内容的模板方法生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com