Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do parentheses make a difference when initializing an empty vector? [duplicate]

I'm having trouble understanding an error. I'm working with a straightforward map of vectors (keyed by strings and storing vectors of strings):

typedef std::map<std::string, std::vector<std::string> > TRouteMarkets;

The following code (stripped down),

void CFoo::Bar(const char* route, const char* market)
{
    // ...

    TRouteMarkets::key_type key(route);
    TRouteMarkets::mapped_type mapped();
    TRouteMarkets::value_type pair(key, mapped);

    // ...
}

produces the following error:

"Foo.cc", line 518: Error: Could not find a match for std::pair<const std::string, std::vector<std::string>>::pair(const std::string, std::vector<std::string>()) needed in CFoo::Bar(const char*, const char*).

But removing the () from mapped, i.e.

TRouteMarkets::mapped_type mapped;

fixes the error. Why? Isn't mapped an empty vector of strings in either case?

like image 321
slackwing Avatar asked Apr 26 '13 14:04

slackwing


2 Answers

This is actually a function declaration:

TRouteMarkets::mapped_type mapped();

declaring a function named mapped that accepts no arguments and returns a TRouteMarkets::mapped_type.

like image 175
hmjd Avatar answered Nov 04 '22 12:11

hmjd


You've run into the Most Vexing Parse problem.

TRouteMarkets::mapped_type mapped();

The above line is declaring a function named mapped that takes no arguments and returns an object of type TRouteMarkets::mapped_type.

With C++11, you can use uniform initialization syntax to avoid this problem.

TRouteMarkets::mapped_type mapped{}; // Not a function declaration anymore
like image 5
Praetorian Avatar answered Nov 04 '22 12:11

Praetorian