C + + standard conversion operator const_cast

Source: Internet
Author: User
Tags modifier

Earlier, C + + inherited and extended the traditional type conversion of C language, and finally left some on the pointer and reference on the transformation problem, did not do in detail to tell. C++compared to C is an object-oriented language, one of the most important features of object-oriented is the polymorphism (polymorphism). In order to use polymorphism very well, it is unavoidable to use pointers and references, but also inevitably encounter the problem of conversion, so in this article, the instructor and on-line repeated access to understand the knowledge summed up. C++Four conversion operators are available: 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 template methods. These methods are provided to developers to use for pointers and reference conversions. In fact, I have long wanted to write this content, I constantly look at the tutor sent the information, but also on the Internet to see the relevant knowledge, but has been slow to fully understand C++the use of conversion operators, but after reading the data, wrote a traditional translation of the content. While it's literally a good understanding of what it's about, it's really like using it, but it's not exactly what they're used for, it's just a constant reminder of the error by the compiler. So if the understanding is not in place or the wrong place, but also hope that the predecessor or the other can correct. In my opinion, the function of these standard operators is to replace the traditional operators in order to achieve unity. It's like we use Std::endl to output line breaks, not'\ n'. I will use code to illustrate how these standard operators can be used for the corresponding traditional conversions. Of course, this is a general understanding, on the standard operators, the compiler certainly has to do more processing, especially dynamic_cast is not used in the traditional conversion method to fully implement. In this article, I will first talk about my understanding of the const_cast operator. The const_cast (expression) const_cast conversion is a const or volatile qualifier used to remove a variable. For the latter, I am not too clear, because it involves the design of multithreading, and I do not have any understanding in this respect. So I'm just speaking about the const aspect of the content. Using the const_cast to remove the const limit for a const variable, we cannot modify its value, which is the most straightforward representation of this qualifier. But what do we want to do to change its content if we're going to violate its limits? The code below is obviously not up to the point:Const intConstant =Ten;intModifier =constant; Because changes to modifier do not affect constant, this implies that the const_cast converter should not be used on the object data, because such conversions result in two variables/object does not have a dependency. Only with pointers or references, so that the variable points to the same address is the solution, but the code below in C++is also compiled in the following:Const intConstant = +;int* Modifier = &constant//error:invalid conversion from ' const int* ' to ' int* '(the top of the code in C can be compiled, up to a warning, where the first step in C can begin to constant the data inside the arbitrary) to the constant to non-const reference is also not possible. Const intConstant = +;int& modifier =constant;//Error:invalid Initialization of reference of type ' int& ' from expression of type ' const int 'so const_cast out to eliminate the const, in order to cause chaos in the procedural world. The code below will be compiled successfully:Const intConstant = +;Const int* Const_p = &constant;int* modifier = const_cast<int*>(const_p);*modifier =7the traditional conversion method implements the Const_cast operator I said, "the quasi-conversion operator can be implemented in a traditional conversion mode." The reason for Const_cast is that C+ + The conversion of the pointer is arbitrary, it does not check the type, any pointers can be converted to each other, so const_cast can directly use the Display transformation (int*) to replace:Const intConstant = +;Const int* Const_p = &constant;int* Modifier = (int*) (const_p); or we can synthesize them into a statement, skip the middle variable, and useConst intConstant = +;int* Modifier = (int*) (&constant); alternativeConst intConstant = +;int* modifier = const_cast<int*> (&constant); Why to remove the Const qualifier as already seen in the previous code, we cannot modify the constant, but we can re-assign a value to the modifier. But is the program world really messed up? Did we really change the value of Constatn through modifier? The data that modifies the const variable is really c++to the purpose of the const? If we print out the results: cout<<"constant:"<< constant <<Endl;cout<<"const_p:"<< *const_p <<Endl;cout<<"modifier:"<< *modifier <<Endl;/**constant:21const_p:7modifier:7**/constant still retains its original value. But they did point to the same address: cout<<"constant:"<< &constant <<Endl;cout<<"const_p:"<< const_p <<Endl;cout<<"modifier:"<< modifier <<Endl;/**constant:0x7fff5fbff72cconst_p:0x7fff5fbff72cmodifier:0x7fff5fbff72c**/It's a strange thing to do, but it's a good thing: Description C++is the const, is the const, the outside world change million, I will not change. Otherwise it will be a mess, and the const does not have the meaning of existence. IBM's C+ + Guide Salutation "*modifier =7;” To "Undefined behavior (Undefined Behavior)". The so-called undefined is to say that this statement is in standard C + +there is no explicit provision in the compiler to decide what to do with it. The left-hand operation of a bitwise operation can also be an undefined behavior, because we are not sure whether the logical left shift or the arithmetic left shift. Another example of the following statement: V[i]= i++Is also an undefined behavior, because we do not know whether to do the self-increment first, or to find the position in the array first. For undefined behavior, all we have to do is avoid such statements. For const data, we have to make sure that the const data is never re-assigned. If we don't want to change the value of the const variable, then why do we go to const? The reason is that we may have called a function with a parameter other than const, and the actual arguments we're going to pass in are really const, but we know that the function doesn't modify the parameters. So we need to use const_cast to remove the const qualifier so that the function can accept the actual argument. #include<iostream>using namespacestd;voidPrinter (int* Val,stringSeperator ="\ n") {cout<< val<<seperator;}intMainvoid) {        Const intConsatant = -; //Printer (consatant);//error:invalid conversion from ' int ' to ' int* 'Printer (const_cast<int*> (&consatant)); return 0;} The reason for this is that it is possible that the method we are calling is written by someone else. Another reason I can think of is when a const object wants to call itself a non-const method, because in a class definition, a const can also be used as an identifier for a function overload. With the opportunity, I'll look at what I know about the use of const, C++The const really has so much to say. In IBM's C++The guide also mentions another scenario where you might want to go to const: #include<iostream>using namespacestd;intMainvoid) {    intVariable = +; int* Const_p = &variable; int* modifier = const_cast<int*>(const_p); *modifier =7cout<<"variable:"<< variable <<Endl; return 0;} /**variable:7**/we define a non-const variable, but use a const-qualified pointer to point to it, where we suddenly want to modify it, but we have pointers on our hands, and we can go to const to modify it. The result of the above code confirms that we have successfully modified it. But I think this is not a good design, or should follow the principle: The use of const_cast to remove the const-qualified purpose is not to modify its content, but only frustration . (If really like I say is kind of helpless, it seems const_cast is not very useful to the time, but I also rarely use it) Director:jim FAWCETTC+ + Language Tutorial-Type castingobject oriented DESIGNIBM complilers-XL/C + + V9.0  forLinux-the const_castoperator(C + +Only ) Stackoverflow:is const_cast Safe?

A. Function Description:
Const_cast < Type-id > (expression)
The main use is to remove the const attribute, but you can also add the const attribute. Mainly use the former, the latter is seldom used.

Remove the const attribute:const_case<int*> (&num), often, because a const variable cannot be assigned directly to a non-const variable and must be converted.

Add the Const attribute: const int* k = Const_case<const int*> (j), which is rarely used because a non-const variable can be assigned directly to a const variable, such as: const int* k = j;

Two. Scope of use:1The . Constant pointer is converted to a non-const pointer, and the pointer points to the original variable (that is, the converted pointer address is unchanged). [CPP] View plaincopyclassA { Public: A () {M_inum=0; }             Public:         intM_inum;            }; voidfoo () {//1. Pointer to class    ConstA *PCA1 =NewA; A*PA2 = const_cast<a*> (PCA1);//constant objects are converted to very mass objectsPa2->m_inum = $;//Fine//the pointer points to the original object after the conversioncout<< Pca1->m_inum <<pa2->m_iNum<<endl;// $//2. Pointer to basic type    Const intICA = -; int* ia = const_cast<int*> (&ICA); *ia = $; cout<< *ia <<ica<<endl;// $}  2The . Constant reference is converted to a very literal reference. [CPP] View plaincopyclassA { Public: A () {M_inum=1; }     Public:intM_inum;    }; voidfoo () {A a0; ConstA &AMP;A1 =A0; A A2= const_cast<a&> (A1);//constant reference to very referenceA2.m_inum= $;//Finecout<< a0.m_inum << a1.m_inum << a2.m_inum << Endl;//1 1}  2A constant object (or base type) cannot be converted to a non-const object (or base type). [C-Sharp ] View plaincopyvoidfoo () {//An error occurred when a constant object was converted to a very mass object ConstA CA; A A= const_cast<a> (CA);//not allowed   Const inti = -; intj = const_cast<int> (i);//not allowedRemember that this conversion only opens an interface, not a substantial conversion. (In fact, it is actually converted, but the expression is not allowed to write this)3. Add the const attribute [C-Sharp ] View plaincopyintMainintargcChar**argv_) {   inti = -; int*j = &i; Const int*k = const_cast<Const int*>(j); //const int *m = j; It's almost like it's written .//It means the same address.cout <<i<<","<<&i<<endl;//0012ff78,cout <<*j<<","<<j<<endl;//0012ff78,cout <<*k<<","<<k<<endl;//0012ff78,*j = $; //*k = 200; //Error   return 0; } three. Summary:1using Const_cast to remove the const attribute does not really change the const property of the original class type (or base type), it simply provides an interface (pointer or reference) that allows you to change the value of the type through this interface. Maybe that's one reason const_case can only convert pointers or references. 2. Adding a const property using Const_case also provides an interface to not modify its value, but this added const operation has no practical purpose (perhaps I know too shallow).

C + + standard conversion operator const_cast

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.