C + + temporary materialization

Source: Internet
Author: User

Consider the following code:

structS { Public: S (inti) {m=i; }    ~S () {std::cout<<"~s () called \ n"; }    intm;};voidFun (s s) {std::cout<<"Fun called \ n";}intMain () {fun (S) (1));}

S (1) is constructed once, is a nameless temporary object (it is named TMP), and then passed to the fun function, S is another local object. So the program should print two times ~s () called. (measured vs2015 printed 2 times, only once in GCC and clang)

C++17 Start, S (1) This pure right value is not necessarily materialized to TMP, meaning that in this program, there is no TMP object created at all. Therefore, in a compiler supported by C++17, only one ~s () called is printed.

This is not the compiler's free choice of optimization technology, compiler optimization technology that the S (1) and fun (s) in S is one thing, directly on the structure of s to fuss. (see "Inside C + + Model")

C++17 Mandatory Prvalue is just the initialization semantics, meaning that prvalue can only help other objects to initialize, they can not easily materialized. Here, Fun (S (1)) did not occur temporary materialization. So, when will it happen? For example:

int k = Fun (). m;

In this way, the pure right value returned by the fun () is not materialized, because the object m to access it.

Other physicochemical conditions, see http://en.cppreference.com/w/cpp/language/implicit_conversion#Temporary_materialization

C + + temporary materialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.