1

I'm trying to initialize a vector with an explicit allocator, but the code below seems not working:

vector<int> a1(allocator<int>()); cout << a1.size(); //Error C2228: left of '.size' must have class/struct/union 

There is also a working version:

vector<int> a2(*(new allocator<int>())); cout << a2.size(); // OK 

And another:

vector<int> a3(a2, allocator<int>()); cout << a3,size(); // OK 

I want to know why only the first version is not working. I'm using MSVC with C++17, and it seems the compiler won't regard a1 as an object. Thanks.

5
  • 4
    a1 is a function declaration. You fell victim to the most vexing parse. Commented Apr 18, 2021 at 21:21
  • @HolyBlackCat Thanks a lot! I'm new to this terminology actually. I will check to figure out how it works. Commented Apr 18, 2021 at 21:27
  • have you tried vector<int> a1( allocator<int>{ } ); ? Commented Apr 18, 2021 at 22:23
  • 1
    google "most vexing parse". Commented Apr 18, 2021 at 22:26
  • @AlessandroTeruzzi Thanks, this one works! Commented Apr 20, 2021 at 21:48

1 Answer 1

1

Thanks to everyone who gives me suggestions, this is known as "most vexing parse" and can be fixed by uniform initialization as:

vector<int> a1(allocator<int>{}); 

So that a1 is now a vector. Otherwise, a1 will be interpreted as a function, that receives a parameter of type std::allocator<int> (*)() and returns vector<int>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.