这是不正确的警告吗? [英] Is this an incorrect warning?

查看:230
本文介绍了这是不正确的警告吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看我经常看到的这种代码模式:

Let's see this code pattern I'm seeing often:

struct Foo
{
    template <typename T>
    T* as1() { /* ... */ }

    template <typename T>
    T* as2(T*) { /* ... */ }  
};   

前一种方法应像这样使用:

The former method is to be used like this:

    SomeComplexTypeAndNotAuto * a = foo.as1<SomeComplexTypeAndNotAuto>();

虽然后者更易于使用,因为您无需重复复杂的类型:

While the latter is more convenient to use since you don't need to repeat the complex type:

    SomeComplexTypeAndNotAuto * a = foo.as2(a); 

但是,大多数编译器以Wuninitialized警告拒绝第二种情况:

However, most compiler rejects the 2nd case with a Wuninitialized warning:

warning: variable 'a' is uninitialized when used within its own initialization [-Wuninitialized]

很显然,变量未在初始化中使用,仅使用了类型。有没有一种方法可以避免这种警告而无需处理每个编译器实用程序的地狱?

It's quite clear the variable is not used in the initialization, only its type is. Is there a way to avoid this warning without dealing with the hell of per-compiler pragma ?

编辑:

从我的最初帖子中还不清楚,但是当我写 SomeComplexTypeNotAuto 时,我的意思是这样的代码:
auto a = foo.as2(a); 无法解析,因为您必须提供一种允许编译器推断的类型。

It's not clear from my initial post, but when I wrote SomeComplexTypeNotAuto, I meant that such code like this: auto a = foo.as2(a); can not be resolved since you have to provide one type to allow the compiler to deduce it.

我的问题特定于以下事实:方法 as2()是模板,因此必须可见在专业化时间为类型 T 。因此,编译器可以看到参数 T * 甚至都没有名称,因此该函数无法使用/使用。因此,我不明白为什么它会警告未使用的变量警告,因为很明显它未被使用。

My question was specific to the fact that method as2() is a template, as as such must be visible at specialization time for a type T. So the compiler can see that the argument T* does not even have a name so it's not used/usable from within the function. As such, I don't get why it warns about the "unused variable" warning since it's clear it's not used.

推荐答案


很明显,变量没有在初始化中使用

It's quite clear the variable is not used in the initialization

相反,很明显 变量用于函数参数的初始化。程序的行为是不确定的。

On the contrary, it is quite clear that the variable is used in the initialisation of the function argument. The behaviour of the program is undefined.


这是不正确的警告吗?

Is this an incorrect warning?

否,警告是正确的。

一个简单的解决方法是更改​​参数

A simple fix is to change the argument into a reference:

T* as2(T*&)

请务必确保不实际读取参考值。

Just be extra sure to not actually read the referred value.

自C + 11起,您可以使用 auto 代替。

Since C+11, you can use auto instead however.

这篇关于这是不正确的警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆