相关疑难解决方法(0)

为什么auto x {3}推导出initializer_list?

我喜欢autoC++ 11.太棒了.但它有一个不一致,真的让我紧张,因为我一直绊倒它:

int i = 3;       // i is an int with value 3
int i = int{3};  // i is an int with value 3
int i(3);        // i is an int with value 3 (possibly narrowing, not in this case)
int i{3};        // i is an int with value 3

auto i = 3;      // i is an int with value 3
auto i = int{3}; // i is an int with value 3
auto i(3); …
Run Code Online (Sandbox Code Playgroud)

c++ initializer-list auto c++11 type-deduction

56
推荐指数
1
解决办法
4532
查看次数

表达式的不同编译器行为:auto p {make_pointer()};

以下程序的正确行为是什么?

// example.cpp

#include <iostream>
#include <memory>

struct Foo {
  void Bar() const {
    std::cout << "Foo::Bar()" << std::endl;
  }
};

std::shared_ptr<Foo> MakeFoo() {
  return std::make_shared<Foo>();
}

int main() {
  auto p { MakeFoo() };
  p->Bar();  
}
Run Code Online (Sandbox Code Playgroud)

当我在Linux RHEL 6.6工作站中编译它时,我得到以下结果:

$ g++ -v
gcc version 5.1.0 (GCC)
$ g++ example.cpp -std=c++14 -Wall -Wextra -pedantic
$ ./a.out
Foo::Bar()
Run Code Online (Sandbox Code Playgroud)

$ clang++ -v
clang version 3.6.0 (trunk 217965)
$ clang++ example.cpp -std=c++14 -Wall -Wextra -pedantic
example.cpp:16:4: error: member reference type 'std::initializer_list<std::shared_ptr<Foo> >' …
Run Code Online (Sandbox Code Playgroud)

c++ g++ icc clang++ c++14

15
推荐指数
1
解决办法
814
查看次数

标签 统计

c++ ×2

auto ×1

c++11 ×1

c++14 ×1

clang++ ×1

g++ ×1

icc ×1

initializer-list ×1

type-deduction ×1