1

I have a class A

struct A
{
    A() = delete;
    A(const A&) = default;
    A& operator=(const A&) = default;
    A(A&&) = default;
    A& operator=(A&&) = default;

    explicit A(int i) ....
    // a few explicit constructors
}

when I am trying to get strcut A that is stored in unordered_map as below:

auto a = my_map[key_];

I get

illegal use of deleted method

error. my understanding was that this is a copy construction, but I do not know why compiler calls the default constructor before the assignement.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
apramc
  • 1,346
  • 1
  • 15
  • 30
  • 3
    A map's `operator[]` requires the value type to have a default constructor so it can create an entry in case the key doesn't exist. What you should do is something like `auto i = my_map.find(key_); if (i != my_map.end()) { auto& val = i->second; ... } else { handle_non_existent_key(); }` – Daniel Schepler Mar 14 '18 at 19:30
  • Read the [documentation](http://en.cppreference.com/w/cpp/container/unordered_map/operator_at): *"When the default allocator is used, this means that key_type must be MoveConstructible and mapped_type must be DefaultConstructible. "* – clcto Mar 14 '18 at 19:31

1 Answers1

5

From http://en.cppreference.com/w/cpp/container/map/operator_at:

mapped_type must meet the requirements of CopyConstructible and DefaultConstructible.

Since the default constructor is deleted, the compiler rightly reports the error.

Further down in the linked page:

Return value

Reference to the mapped value of the new element if no element with key key existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to key.

The function inserts a new element if no element with the given key existed. A default constructor is needed to be able to insert a new element.

R Sahu
  • 204,454
  • 14
  • 159
  • 270