kvrocks icon indicating copy to clipboard operation
kvrocks copied to clipboard

Proposal: Just return values instead of passing pointers if possible

Open PragmaTwice opened this issue 3 years ago • 1 comments

Search before asking

  • [X] I had searched in the issues and found no similar issues.

Motivation

C++ specifies a number of strategies in the standard to eliminate unnecessary copies, which are called copy elision.

One of these optimizations is called named return value optimization (NRVO), which is defined in the standard. This optimization works on the return value, in short, the returned object is not copied onto the current stack.

GCC and Clang both perform this optimization by default (even in the -O0 case). The following simple code demonstrates it:

T f() {
    T a;
    ... // operations on a
    return a;
}
 
T a = f(); // T::T(const T&) or T::T(T&&) will not be called

You can view the assembly or modify and execute this code online on godbolt.

So passing pointers to optimize efficiency maybe not necessary, and returning values is usually easier to make the operation be expressed in the same expression and more intuitive. Some parts of this project use this approach, like these functions.

So I think it would be better to change them to return the results directly.

Solution

No response

Are you willing to submit a PR?

  • [X] I'm willing to submit a PR!

PragmaTwice avatar May 15 '22 09:05 PragmaTwice

Cool, thanks @PragmaTwice. We use many C style passing pointers in function parameter, it's good to me since it won't affect readable.

git-hulk avatar May 15 '22 11:05 git-hulk

Closed as no more insights here. If you find more patterns to adopt, feel free to start a new initiative.

tisonkun avatar Oct 23 '22 03:10 tisonkun