Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code compiles with clang but not with gcc

Tags:

c++

gcc

clang

I have this piece of code that compiles fine with clang (even with -Weverything), but for which gcc issues an error.

#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;
}

and here's what I get when I try to compile the code:

$ 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");
                                                 ^

My gcc version is 4.9.1, and my clang version is 3.5.0. I don't understand why there should even be a shadowing problem. Even if there were, it should have been picked up by clang.

like image 643
user2535797 Avatar asked Jan 31 '15 18:01

user2535797


1 Answers

Change:

PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");

to:

(PhonebookWriter(fname))("Mr Foo Bar","12345")("Mrs Bar Foo","54321");

EXPLANATION

For some reason gcc removes the braces around fname, which turns the line into:

PhonebookWriter fname ("Mr Foo Bar","12345")("Mrs Bar Foo","54321");

And now the errors make sense.

like image 80
Innocent Bystander Avatar answered Oct 04 '22 21:10

Innocent Bystander