使用{}报告未使用的变量进行统一初始化
Uniform initialization with {} reporting unused variable
使用g++4.7.0(-Wall -Wextra -Werror -Wconversion -std=c++11
)编译此代码:
#include <iostream> // std::cout, std::endl
#include <string> // std::string
#include <utility> // std::move
void out(std::string const &message)
{
static int count{0};
std::cout << count++ << " = " << message << std::endl;
}
struct Foo
{
Foo() {out("constructor");}
~Foo() {out("destructor");}
Foo(Foo const &) {out("copy constructor");}
Foo & operator=(Foo const &) {out("copy via assignment"); return *this;}
Foo(Foo &&) {out("move constructor");}
Foo & operator=(Foo &&) {out("move via assignment"); return *this;}
};
int main()
{
auto bar{std::move(Foo())};
out("exiting main");
}
导致以下错误:
error: unused variable 'bar' [-Werror=unused-variable]
我可以通过将bar
初始化更改为以下任一项来消除错误:
/* 0 */ auto bar(std::move(Foo()));
/* 1 */ Foo bar{std::move(Foo())};
/* 2 */ Foo bar(std::move(Foo()));
/* 3 */ auto bar = std::move(Foo());
/* 4 */ Foo bar = std::move(Foo());
/* 5 */ auto bar __attribute__((unused)) {std::move(Foo())};
一旦更改了bar
初始化,输出总是:
0 = constructor
1 = move constructor
2 = destructor
3 = exiting main
4 = destructor
为什么原始bar
初始化报告一个未使用的变量?
auto bar{std::move(Foo())};
在此声明之后,bar
的类型为std::initializer_list<Foo>
,它具有琐碎的复制/移动操作和析构函数。您的其他申报
auto bar(std::move(Foo()));
Foo bar{std::move(Foo())};
Foo bar(std::move(Foo()));
auto bar = std::move(Foo());
Foo bar = std::move(Foo());
将bar
声明为Foo
或Foo&&
,这会抑制警告,因为它具有非平凡的特殊成员函数。
除非您特别打算创建std::inializer_list
对象,否则通常不希望使用auto
进行支持初始化。
嗯,bar
未使用。您可能想要为编译器提交一个缺陷,因为在其他情况下,这似乎是错误地未被检测到的。
相关文章:
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- 在 C++ 中访问 lambda 捕获初始化变量
- 为什么C++不支持对未初始化变量进行智能分析?
- 使用 clang++ 和 g++ 在C++中初始化变量
- C++使用 lambda 初始化变量
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++ - 输出与初始化变量不同?
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- C++ 中的初始化变量
- C++中未初始化变量的值
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 我想知道在构造函数中初始化变量时的生命周期
- 读取恰好具有良好值的未初始化变量
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 为什么在 c++ 中有多种初始化变量的方法
- 没有参数的默认构造函数是否总是初始化变量?
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 使用构造函数跳闸UB的新放置后使用初始化变量