Is it possible to take a parameter by const reference, while banning conversions so that temporaries aren't passed instead?

后端 未结 6 1451
面向向阳花
面向向阳花 2021-01-18 21:58

Sometimes we like to take a large parameter by reference, and also to make the reference const if possible to advertize that it is an input parameter. But by making the refe

6条回答
  •  再見小時候
    2021-01-18 22:27

    You can't, and even if you could, it probably wouldn't help much. Consider:

    void another(long const& l)
    {
        bar_const(l);
    }
    

    Even if you could somehow prevent the binding to a temporary as input to bar_const, functions like another could be called with the reference bound to a temporary, and you'd end up in the same situation.

    If you can't accept a temporary, you'll need to use a reference to a non-const, or a pointer:

    void bar_const(long const* l);
    

    requires an lvalue to initialize it. Of course, a function like

    void another(long const& l)
    {
        bar_const(&l);
    }
    

    will still cause problems. But if you globally adopt the convention to use a pointer if object lifetime must extend beyond the end of the call, then hopefully the author of another will think about why he's taking the address, and avoid it.

提交回复
热议问题