What different between object created from initialization constructor and assign operator?

时间:2016-02-03 02:43:06

标签: c++ c++11

Compiler is GCC 4.8.4 with -std=c++11 flag assigned.

I've got a compile error while compiling a very sample project.

ifstream f(this->pid_file_name());
string content(istreambuf_iterator<char>(f), istreambuf_iterator<char>());
pid_t pid = stoi(content);

It will pop up error like this :

error: no matching function for call to ‘stoi(std::string (&)(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)()))’
     pid_t pid = stoi(content);

However, if I change string declaration like this, every things goes fine :

ifstream f(this->pid_file_name());
string content = string(istreambuf_iterator<char>(f), istreambuf_iterator<char>());

pid_t pid = stoi(content);

I know there are differents by the way how we create a object instance, but I think they should be the same, I have no idea why initialization constructor can't work. Do anyone have idea on this?

1 个答案:

答案 0 :(得分:4)

This is actually a function declaration:

string content(istreambuf_iterator<char>(f), istreambuf_iterator<char>());

See Most vexing parse

One way to fix it is to use universal initialization syntax:

string content{istreambuf_iterator<char>(f), istreambuf_iterator<char>()};