Mat*_*iff 6 c++ g++ uniform-initialization c++11
使用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");
}
Run Code Online (Sandbox Code Playgroud)
...导致以下错误:
error: unused variable 'bar' [-Werror=unused-variable]
Run Code Online (Sandbox Code Playgroud)
我可以通过将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())};
Run Code Online (Sandbox Code Playgroud)
一旦bar初始化已经改变,输出始终:
0 = constructor
1 = move constructor
2 = destructor
3 = exiting main
4 = destructor
Run Code Online (Sandbox Code Playgroud)
为什么原始bar初始化报告未使用的变量?
auto bar{std::move(Foo())};
Run Code Online (Sandbox Code Playgroud)
在此声明之后,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());
Run Code Online (Sandbox Code Playgroud)
声明bar为Foo或Foo&&,它抑制警告,因为它具有重要的特殊成员函数.
auto除非您专门打算创建std::inializer_list对象,否则通常不希望使用支撑初始化.
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |