mardi 27 décembre 2016

gcc when compiling c++ does not complain about c99 designated initializer

// initializer_list.cpp

#include <iostream>
using namespace std;

class Object {
public:
  Object(int i1, int i2) :i1(i1), i2(i2), i3(0) {
    cout << "Object initializer called" << endl;
  }

  int i1, i2, i3;
};

int main() {
  // In our thoughts, after this, obj.i1 should be 1
  // But with g++, obj.i1 = 2, obj.i2 = 1.
  // With clang++, this is syntax error.
  Object obj = {.i2 = 2, .i1 = 1};
  cout << "i1 = " << obj.i1 << ", i2 = " << obj.i2 << endl;
  return 0;
}

Compiled with GCC 6.2:

$g++ -std=c++11 ../initializer_list.cpp
$./a.out

Result:

Object initializer called
i1 = 2, i2 = 1

Compile with clang 3.8:

$ clang++ -std=c++11 ../initializer_list.cpp

../initializer_list.cpp:17:10: error: no matching constructor for initialization of
      'Object'
  Object obj = {.i2 = 2, .i1 = 1};
         ^     ~~~~~~~~~~~~~~~~~~
../initializer_list.cpp:6:3: note: candidate constructor not viable: cannot convert
      argument of incomplete type 'void' to 'int'
  Object(int i1, int i2) :i1(i1), i2(i2), i3(0) {
  ^
../initializer_list.cpp:4:7: note: candidate constructor (the implicit copy
      constructor) not viable: requires 1 argument, but 2 were provided
class Object {
      ^
../initializer_list.cpp:4:7: note: candidate constructor (the implicit move
      constructor) not viable: requires 1 argument, but 2 were provided
1 error generated.

Here is my gcc and clang version. I'm running Ubuntu 16.10.

> g++ --version
g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

> clang++ --version
clang version 3.8.1-12ubuntu1 (tags/RELEASE_381/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
}}

When I search on Google, it(Why does C++11 not support designated initializer list as C99?) says designated initialization is only supported on C99 not C++. So I think this should be a syntax error, but it compiles and run, with an unexpected result. Is this a gcc bug or gcc extension to C++ or others?

Aucun commentaire:

Enregistrer un commentaire