When I attempt to compile this code
class t
{
public:
int v;
// t() = default;
t(int i) : v{i} {}
};
// Driver code
int main()
{
unordered_map<int, t> test;
test.emplace(1, 4);
std::cout << test[1].v << std::endl;
}
I get the error
^
test.cpp:39:20: note: in instantiation of member function 'std::__1::unordered_map<int, t, std::__1::hash<int>, std::__1::equal_to<int>,
std::__1::allocator<std::__1::pair<const int, t> > >::operator[]' requested here
std::cout << test[1].v << std::endl;
^
test.cpp:30:3: note: candidate constructor not viable: requires single argument 'i', but no arguments were provided
t(int i) : v{i} {}
^
test.cpp:25:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class t
^
test.cpp:25:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
When I uncomment the t() = default
line, the code compiles and the output is 4
as expected. The value for the key 1
was already constructed with test.emplace(1, 4);
. So when I do test[1]
, shouldn't this be returning a reference to an instantiated t
object? Why is it trying to default construct the object?