使用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
初始化会报告未使用的变量?
-Werror
选项,而使用了“错误”的代码版本,那么在运行时会发生什么? - John Zwinck