展开std :: reference_wrapper的成本

Per*_*-lk 1 c++ performance wrapper indirection

鉴于:

#include <iostream>
#include <functional>

template<class T> // Just for overloading purposes
struct behaviour1 : std::reference_wrapper<T const>
{
    using base_t = std::reference_wrapper<T const>;
    using base_t::base_t;

    // This wrapper will never outlive the temporary
    // if used correctly
    behaviour1(T&& t) : base_t(t) {}
};

template<class T>
behaviour1(T&&) -> behaviour1<std::decay_t<T> >;

struct os_wrapper : std::reference_wrapper<std::ostream>
{
    using std::reference_wrapper<std::ostream>::reference_wrapper;

    template<class T>
    os_wrapper& operator<<(behaviour1<T> const& v)
    {
        *this << v.get(); // #1
        return *this;
    }

    template<class U>
    os_wrapper& operator<<(U&& t)
    { this->get() << t; return *this; }
};

int main() { os_wrapper(std::cout) << behaviour1(3); }
Run Code Online (Sandbox Code Playgroud)

在第1行中,是实际执行的间接,给定特定用例(一个无法解开的包装器,也不复制也不绑定到除函数参数之外的本地引用),或者编译器只是检测到该对象是inmediatly unwrapped和只是使用原始对象?否则这将是一个更好的设计(例如,对于只保存对象副本的标量类型的部分特化是否会更有效)?

我特别感兴趣gcc(版本7 -O3 -std=c++17),虽然我猜两个clanggcc执行类似的优化技术.

Max*_*kin 5

std::reference_wrapper在优化构建中使用方法的预期成本为0,因为所有std::reference_wrapper代码都可以内联.声明的汇编输出os_wrapper(std::cout) << behaviour1(3);:

movl    $3, %esi
movl    std::cout, %edi
call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
Run Code Online (Sandbox Code Playgroud)

内联是Stroustrup喜欢提及的零开销抽象的内容.