c – 使用{}报告未使用变量的统一初始化

使用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]

我可以通过将栏初始化更改为以下任何一项来删除错误

/* 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())};

更改了条形图初始化后,输出始终为:

0 = constructor
1 = move constructor
2 = destructor
3 = exiting main
4 = destructor

为什么原始条形初始化会报告未使用的变量?

解决方法

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进行支持初始化.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...