Search code examples
c++c++11c++14deleted-functions

illegal use of deleted function


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.


Solution

  • 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.