代码用clang编译但不用gcc编译

use*_*797 4 c++ gcc clang

我有这段代码可以用clang(甚至是-Weverything)编译好,但gcc会发出错误.

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class PhonebookWriter
{
public:

  PhonebookWriter(const string& fname):
    fname_(fname), names_(), numbers_() {}

  PhonebookWriter& operator()(const string& name,
                  const string& number)
  {
    names_.push_back(name);
    numbers_.push_back(number);
    return *this;
  }

  ~PhonebookWriter(void)
  {
    ofstream f(fname_.c_str());
    for(size_t i=0;i<names_.size();++i)
      f << names_[i] << " " << numbers_[i] << "\n";
    f.close();
  }

private:
  const string fname_;
  vector<string> names_;
  vector<string> numbers_;
};

namespace {
  void write_guests_data(const string& fname)
  {
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
  }
}

int main(void)
{
  write_guests_data("phone_book.txt");

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试编译代码时得到的结果:

$ g++ ./test.cpp
./test.cpp: In function ‘void {anonymous}::write_guests_data(const string&)’:
./test.cpp:39:27: error: declaration of ‘PhonebookWriter fname’ shadows a parameter
     PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
                           ^
./test.cpp:39:48: error: no matching function for call to ‘PhonebookWriter::PhonebookWriter(const char [11], const char [6])’
     PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
                                                ^
./test.cpp:39:48: note: candidates are:
./test.cpp:11:3: note: PhonebookWriter::PhonebookWriter(const string&)
   PhonebookWriter(const string& fname):
   ^
./test.cpp:11:3: note:   candidate expects 1 argument, 2 provided
./test.cpp:7:7: note: PhonebookWriter::PhonebookWriter(const PhonebookWriter&)
 class PhonebookWriter
       ^
./test.cpp:7:7: note:   candidate expects 1 argument, 2 provided
./test.cpp:39:49: error: expected ‘,’ or ‘;’ before ‘(’ token
     PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
                                                 ^
Run Code Online (Sandbox Code Playgroud)

我的gcc版本是4.9.1,我的clang版本是3.5.0.我不明白为什么甚至会出现阴影问题.即使有,它应该被clang拾取.

Inn*_*der 8

更改:

PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
Run Code Online (Sandbox Code Playgroud)

至:

(PhonebookWriter(fname))("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
Run Code Online (Sandbox Code Playgroud)

说明

出于某种原因,gcc删除了大括号fname,将行转换为:

PhonebookWriter fname ("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
Run Code Online (Sandbox Code Playgroud)

现在错误是有道理的.