Unified initialization with {} representing an unused variable

Compiling this code with 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"); } 

... results in the following error:

 error: unused variable 'bar' [-Werror=unused-variable] 

I can remove the error by changing the initialization of bar to any of the following:

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

After the bar initialization has been changed, the output is always:

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

Why does the initial bar initialization report an unused variable?

+6
source share
2 answers
 auto bar{std::move(Foo())}; 

After this declaration, bar is of type std::initializer_list<Foo> , which has trivial copy / move operations and a destructor. Other announcements

 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()); 

declare bar as Foo or Foo&& , which suppresses the warning because it has non-trivial special member functions.

Usually you do not need initialization with auto unless you specifically intend to create a std::inializer_list .

+8
source

Well, bar not used. You might want to write a defect for the compiler, as this seems to mistakenly go unnoticed in other situations.

+2
source

Source: https://habr.com/ru/post/911038/


All Articles