Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

Is There performance difference between this three function return ways (c++)

A Function1()
{
    return {1};
}

A Function2()
{
    return A{1};
}

A Function3()
{
    A a{1};
    return a;
}

i tried three ways. they all call just one assignment constructor.

i question There can be performance difference depending on which complier to use?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are subtle differences:

  • Function1 requires non explicit A's constructor. construct A "in place" (even before C++17). so copy/move A's constructor might even be marked as = delete, and program is well formed.

  • pre-C++17, Function2 will use move/copy constructor which might be elided (return value optimization: RVO) (copy/move constructor should be available though (marking as = delete won't compile)).
    Post C++17, no move/copy are done (similar to Function1, but work with explicit constructors).

  • Function3 will use move/copy constructor which might be elided (named return value optimization: NRVO).

With correct options, compilers will do the optimization, and all should be equivalent.

With options such as -fno-elide-constructors, pre-c++17, Function1 should win, post C++17, Function1 and Function2 should win.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...