C++ Initializing unique_ptr in nested map, compilation error?

Viewed 131

I understand unique_ptr can only be move constructed and move assigned, but the following code still puzzles me,

#include <map>
#include <memory>
#include <utility>

using namespace std;

int main()
{
    map<int, unique_ptr<int>> a{}; // 1, OK
    map<int, map<int, unique_ptr<int>>> b{{1, {}}}; // 2, error, copy ctor accessed

    map<int, map<int, unique_ptr<int>>> d; // 3, workaround
    d.try_emplace(1, move(map<int, unique_ptr<int>>{})); // 4 workaround
}

Of line 1 through 4, only line 2 fails to compile, and I think it means somewhere the unique_ptr's copy ctor is accessed.

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’

But I am not trying to instantiate a unique_ptr here at all. I can buy the theory that line 1 is merely calling default ctors, so it is not a good reference to compare, but still, in line 2 I am only instantiating an empty inner map object, which should not instantiate a unique_ptr.

My limited understanding of initializer list is that copy ctor is involved (maybe more than once?) . But again, in this example, shouldn't the innner map be initialized as an empty map therefore unique_ptr's ctor should not be invoked?

Btw my workaround is line 3 and 4, so far they seem to work, but still would like to understand why line 2 fails.

0 Answers
Related