微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/111679.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐