Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c++ - Create std::string from std::istreambuf_iterator, strange syntax quirk

I found somewhere the following idiom for reading a file into a string:

std::ifstream file("path/to/some/file.ext");
std::string contents(
    std::istreambuf_iterator<char>(file),
    (std::istreambuf_iterator<char>())
);

Which works just fine as it is. However, if I remove the parentheses around the second iterator argument, that is:

std::string contents(
    std::istreambuf_iterator<char>(file),
    std::istreambuf_iterator<char>()
);

As soon as I try to call any method on the string object, for example:

const char *buffer = contents.c_str();

I get a compile error of the form:

error: request for member 'c_str' in 'contents', which is of non-class type 'std::string(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)()) {aka std::basic_string<char>(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())}'

Also if I try to assign that string to another:

std::string contents2 = contents;

I get an error of the form:

error: conversion from 'std::string(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)()) {aka std::basic_string<char>(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())}' to non-scalar type 'std::string {aka std::basic_string<char>}' requested

Why is this? I can see no reason for those parentheses being needed, much less affect the type definition of the contents variable. I am using g++ 4.8.2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is an example of Most Vexing Parse:

std::string contents(
    std::istreambuf_iterator<char>(file),
    std::istreambuf_iterator<char>()
);

The statement is parsed as the declaration of a function named contents that takes two parameters. One parameter that is a variable named file of type std::istreambuf_iterator, and a second one that is a function that takes no arguments and returns an std::istreambuf_iterator. Specification of function parameter names are optional.

Wrapping at least one of the expressions in parenthesis causes it to be parsed as a variable definition.

C++11 solves this problem with its provision of uniform-initialization:

std::string contents{std::istreambuf_iterator<char>{file}, {}};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...