C ++ standard conversion operator const_cast

Source: Internet
Author: User

Previously, I talked about the traditional type conversion method of C language inherited and extended by C ++, and finally left some conversions on pointers and references. Compared with C, C ++ is an object-oriented language. One of the biggest characteristics of object-oriented is its "polymorphism )".

If we want to use polymorphism well, we will inevitably use pointers and references, and we will inevitably encounter conversion problems. Therefore, in this article, I will summarize my tutor's lecture and the knowledge I learned on the Internet.

C ++ provides four conversion operators:

    • Const_cast <new_type> (expression)
    • Static_cast <new_type> (expression)
    • Reinterpret_cast <new_type> (expression)
    • Dynamic_cast <new_type> (expression)

They have the same structure and look like a template method. These methods are provided for developers to convert pointers and references.

As a matter of fact, I wanted to write this article for a long time. I kept reading the information from my tutor and reading related knowledge on the Internet, however, I have been unable to fully understand the usage of the C ++ conversion operator for a long time. I wrote a traditional conversion article after reading the documents. Although they are literally quite understandable about what they do, they are actually used, but they don't know their specific purpose, and will only be repeatedly reminded by the compiler.Error. Therefore, if you do not understand what is not in place or wrong, you still hope that the predecessors or newcomers can correct the problem.

In my opinion, these standard operators are used to replace traditional operators for unification. Just like we use STD: Endl to output line breaks, rather than '\ n '. I will useCodeTo describe how the standard operators can be used for the traditional conversion. Of course, this is a general understanding. In terms of standard operators, the compiler must do more processing. In particular, dynamic_cast cannot be fully implemented using traditional conversion methods.

In this articleArticleI will first talk about my understanding of the const_cast operator.

Const_cast (Expression)

The const_cast Delimiter is the const or volatile qualifier used to remove the variable.I am not very clear about the latter, because it involves multi-threaded design, and I do not know much about it. So I only talk about const content.

Use const_cast to remove const limitation

For a const variable, we cannot modify its value, which is the most direct manifestation of this qualifier. But what should we do if we want to modify its content against its limits?

The following code clearly fails to reach the goal:
Const int constant = 10;
Int modifier = constant;

Because the modification to modifier does not affect constant, this implies that:The const_cast conversion character should not be used on the object data.Because the two variables/objects obtained by such conversion are not correlated.

Only using pointers or references to direct variables to the same address is the solution. Unfortunately, the following code cannot be compiled in C ++:
Const int constant = 21;
Int * modifier = & Constant
// Error: Invalid conversion from 'const int * 'to 'int *'

(The above code can be compiled in C, and a warning is obtained at most. In C, you can start to confuse the data in constant in the previous step)

It is not acceptable to assign a constant to a non-const reference.
Const int constant = 21;
Int & modifier = constant;
// Error: Invalid initialization of reference of Type 'int & 'from expression of type 'const int'

Therefore, const_cast eliminates const to causeProgramChaos in the world.

The following code has been compiled successfully:
Const int constant = 21;
Const int * const_p = & constant;
Int * modifier = const_cast <int *> (const_p );
* Modifier = 7;

Const_cast operator in traditional Conversion Mode

I said:Quasi-conversion operators can be implemented using traditional conversion methods.. The reason for implementing const_cast is thatC ++ converts pointers randomly. It does not check the type, and any pointers can convert each other., So const_cast You can directly use the display conversion (int *) instead:
Const int constant = 21;
Const int * const_p = & constant;
Int * modifier = (int *) (const_p );

Or we can combine them into a statement, skip the intermediate variable, and use
Const int constant = 21;
Int * modifier = (int *) (& constant );

Substitution
Const int constant = 21;
Int * modifier = const_cast <int *> (& constant );

Why remove the const limitation?

As we can see in the previous code, we cannot modify constant, but we can re-assign values to modifier.

But is the program world really messy? Have we actually modified the constatn value through modifier? Is it true that C ++ has gone to the const to modify the data of the const variable?

If we print the result:
Cout<"Constant :"<Constant <Endl;
Cout<"Const_p :"<* Const_p <Endl;
Cout<"Modifier :"<* Modifier <Endl;
/**
Constant: 21
Const_p: 7
Modifier: 7
**/

The original value of constant is retained.

But they do point to the same address:
Cout<"Constant :"<& Constant <Endl;
Cout<"Const_p :"<Const_p <Endl;
Cout<"Modifier :"<Modifier <Endl;

/**
Constant: 0x7fff5fbff72c
Const_p: 0x7fff5fbff72c
Modifier: 0x7fff5fbff72c
**/

This is a strange thing, but it is a good thing:It indicates that const is in C ++, that is, Const. If the external environment is changing, I will not change.. Otherwise, it would be messy, and the const would have no significance.

The ibm c ++ Guide calls "* modifier = 7 ;""Undefined behavior )". The so-calledUndefined. It means that this statement does not have clearly defined in standard C ++, And the compiler determines how to handle it.

The Left shift operation of bitwise operations can also be considered an undefined action, because we are not sure whether it is logical left shift or arithmetic left shift.

For example, the following statement: V [I] = I ++; is also an undefined behavior, because we do not know whether to perform auto-increment first or to find the position in the array first.

What we can do for undefined behaviors is to avoid such statements.For const data, we must ensure that:No value is assigned to the const data.

If we don't want to modify the value of the const variable, why should we go to const?

The reason is that we may call a function whose parameter is not const, but the actual parameter we want to pass in is indeed const, but we know that this function will not modify the parameter. Therefore, we need to use const_cast to remove the const limitation so that the function can accept this actual parameter.

   # include   iostream   using   namespace   STD ;  void  printer ( int  * val,  string  seperator = "\ n ") { cout  
   
     int  main (void) {
     const  
     int  consatant = 20; 
     // printer (consatant); // error: invalid conversion from 'int' to ' int  *'  printer (
     const_cast 
       int  *> (& consatant ));  return  0 ;}
    

The cause of this situation may be that the method we call is written by someone else. Another reason I can think of is that when the const object wants to call its own non-const method, because in the class definition, const can also be used as a identifier for function overloading. If you have the opportunity, I will review the usage of const that I know. There are too many const in C ++.

In the ibm c ++ guide, we also mentioned another situation where const may be required:

 
# Include<Iostream>Using Namespace STD;IntMain (void ){IntVariable = 21;Int* Const_p = & variable;Int* Modifier =Const_cast<Int*> (Const_p); * modifier = 7Cout<"Variable :"<Variable <Endl;Return0 ;}/** Variable: 7 **/

We defined a non-const variable, but pointed to it with a pointer with const limitation. We suddenly wanted to modify it in one place, but we only had a pointer in our hand, at this time, we can go to the const to modify it. The above Code results also confirm that the modification was successful.

However, I think this is not a good design, but we should follow this principle:The purpose of removing the const Limitation Using const_cast is definitely not to modify its content., Just out of helplessness. (If I say it is helpless, it seems that const_cast is not very useful, but I actually seldom use it)

Director: Jim Fawcett
    1. C ++ language tutorial-Type Casting
    2. Object Oriented Design
    3. IBM complilers-xl c/C ++ v9.0 for Linux-The const_cast operator (C ++ only)
    4. Stackoverflow: Is const_cast safe?

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.