Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign empty initializer to vector of unique_ptrs

I have the following code:

std::unordered_map<std::string, std::vector<std::unique_ptr<class EventTrigger>>> triggers;

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = {};
}

That results in an error about using a deleted constructor of unique_ptr. If, on the other hand, I do this, everything compiles fine:

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = std::vector<std::unique_ptr<class EventTrigger>>();
}

Can anyone explain why this is happening? I thought the empty initializer list would have resulted in an empty vector being assigned to triggers[eventName].

like image 865
Crankycyclops Avatar asked Jun 01 '20 02:06

Crankycyclops


1 Answers

triggers[eventName] = {} resolves to vector<T>::operator=(std::initializer_list<T>). This operator requires copying elements from the initializer list to the vector.

triggers[eventName] = std::vector<...>() resolves to vector<T>::operator=(vector<T>&&) - the move assignment operator. This doesn't require copying any elements, just transferring ownership of existing storage.

like image 51
Igor Tandetnik Avatar answered Oct 12 '22 23:10

Igor Tandetnik