Benefits of using reference_wrapper instead of raw pointer in containers?

前端 未结 2 608
南旧
南旧 2021-02-02 10:01

What benefits has using std::reference_wrapper as template parameter of containers instead of raw pointers? That is std::vector

2条回答
  •  终归单人心
    2021-02-02 11:04

    C references are really problematic while working with templates. If you are "lucky" enough to compile code with reference as a template parameter you might have problems with code that would work (for some reason) as follows:

    template f(T x) { g(x); }
    template g(T x) { x++; }
    

    Then even if you call f(x) it will call g. But reference_wrapper works fine with templates.

    As also mentioned earlier - you will have problems with compiling things like vector, but vector> works fine.

提交回复
热议问题