[Valid C ++ Reading Notes] 005 _ clause 05 _ understand which functions C ++ writes and calls in silence

Source: Internet
Author: User

In fact, this is also mentioned in C ++'s basic introductory books, such as C ++ primer, but few people pay attention to it. The author puts forward this point, to remind us.

The content of this clause is as follows 【Code snippet 1After being processed by the compiler, the code you write is essentially 【Code snippet 2]:

Code snippet 1 (manually written by you ):

1 class  A{2 3 };

Code snippet 2 (generated by the compiler for you ):

1 class A{2 public:3     A() { ... }4     A(const A& rhs) { ... }5     ~A() { ... }6 7     A& operator =(const A& rhs) { ... }8 };

As can be seen from the above, the compiler adds a statement for us:

1. No parameter Constructor

2. copy constructors

3. destructor

4. Value assignment operator =

In these terms, the author explains another point, that is, whether to generate or not the assignment operator = generation rules? Let's look at two examples:

 1 #include <iostream> 2 using namespace std; 3  4 class A{ 5 }; 6  7 int main(){ 8     A a1; 9     A a2;10     a1 = a2;11     return 0;12 }

Result: The compilation is successful!

 1 #include <iostream> 2 using namespace std; 3  4 class A{ 5 public: 6     int value; 7     const int constValue; 8     A(int v):constValue(v){} 9 };10 11 int main(){12     A a1(10);13     A a2(20);14     a1 = a2;15     return 0;16 }

Result: The compilation fails, and the message "error: There is no '=' operator matching these operands" is displayed ".

This shows that:

When a constant is defined for a reference in a class, the compiler does not generate a '=' operator for it.

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.