samedi 22 juin 2019

Functions taking rvalue parameters

I've seen quite a lot of code in my company where functions take rvalue arguments.

Example:

void Notifier::PostEvent(std::unique_ptr<IEvent>&& event)
{
    std::unique_lock<std::mutex> lock(m_Mutex);
    m_events.push_back(std::move(event));
    m_conditionVariable.notify_all();
}

There are no templates here. This could easily have written like this:

void Notifier::PostEvent(std::unique_ptr<IEvent> event)
{
    std::unique_lock<std::mutex> lock(m_Mutex);
    m_events.push_back(std::move(event));
    m_conditionVariable.notify_all();
}

Since the parameter 'event' is a sink value in both cases they are effectively the same. I think the only advantage with the first version is that it saves one move constructor for the unique_ptr. Is that correct? Is it really worth it?

Aucun commentaire:

Enregistrer un commentaire