Why should pop() take an argument?

前端 未结 5 806
你的背包
你的背包 2021-02-15 02:09

Quick background
I\'m a Java developer who\'s been playing around with C++ in my free/bored time.

Preface
In C++, you often see

5条回答
  •  你的背包
    2021-02-15 02:45

    The only reason I can see for using this syntax in C++:

    void pop(Item& removed);
    

    is if you're worried about unnecessary copies taking place.

    if you return the Item, it may require an additional copy of the object, which may be expensive.

    In reality, C++ compilers are very good at copy elision, and almost always implement return value optimization (often even when you compile with optimizations disabled), which makes the point moot, and may even mean the simple "return by value" version becomes faster in some cases.

    But if you're into premature optimization (if you're worried that the compiler might not optimize away the copy, even though in practice it will do it), you might argue for "returning" parameters by assigning to a reference parameter.

    More information here

提交回复
热议问题