9

As stated in this answer a std::vector<T> cannot contain const T, or classes with const-members. However, this is not the case when T = std::pair<const int, int>, as shown below. Why is this the case? How is std::pair special?

#include <utility>
#include <vector>

struct foo
{
    const int first;
    int second;
};

int main() {
    std::vector<std::pair<const int, int>> V1;
    V1.resize(3); // This compiles

    std::vector<foo> V2;
    V2.resize(3); // This gives the error listed below
}

error: use of deleted function 'foo::foo()'

note: 'foo::foo()' is implicitly deleted because the default definition would be ill-formed:

Usman
  • 1,983
  • 15
  • 28
Jonas
  • 6,915
  • 8
  • 35
  • 53

1 Answers1

18

You are mixing two things here. The error that you get is due to the implicitly deleted foo() default constructor that std::vector::resize(size_type count) invokes:

If the current size is less than count,
1) additional default-inserted elements are appended

The std::pair template has a default constructor, this is why the call to V1.resize succeeds. If you provide one for foo as well, or allow its implicit generation by in class initialization, e.g.

struct foo
{
    const int first = 42;
    int second = 43;
};

then

std::vector<foo> V2;
V2.resize(3);

will happily compile. The operation that won't work out for both std::pair<const int, int> and foo is assignment. This won't compile:

V1[0] = std::pair<const int, int>(42, 43); // No way
V2[0] = { 42, 43 }; // Also not ok, can't assign to const data member

which doesn't have anything to do with std::vector, but with the const-qualified data members in both cases.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    Isn't it also related to that fact that in C++03 (the Q&A the OP quoted) the requirements were container-wide, while now they are more member function specific? – StoryTeller - Unslander Monica Mar 18 '19 at 10:16
  • @StoryTeller Good question. Comparing the container requirements between two versions of the standard seems a bit above my pay grade, but I'll try to think about it :) – lubgr Mar 18 '19 at 10:28