The difference between const T, const t*, T *const, const t&, const t*&

Source: Internet
Author: User

Here, t refers to a data type, which can be either an int, a long, a doule, or a type class of its own type. A single const You must know that you are referring to a constant, but you are not confused by the many changes that the const unites with other types? Below we hit parse.

Const T

Defines a constant that must be initialized at the same time as the declaration. Once declared, this value will not be changed.

int5;constint10;        //正确constint constInt2 = i;        //正确20;                  //错误,常量值不可被改变constint constInt3;            //错误,未被初始化
Const t*

A pointer to a constant that cannot be used to change the value of the object to which it points.

Const inti =5;Const intI2 =Ten;Const int* PInt = &i;//Correct, point to a const int object, which is the address of I//*pint = 10; Error, cannot change the object that it refers to FouPInt = &i2;//Correct, you can change the value of the pint pointer itself, when pint points to the address of I2Const int* P2 =New int(8);//Correct, point to the address of a new objectDeleteP2;//Correct//int* pInt = &i; Error, I is a const int type, type mismatch, cannot initialize const int * to int *intNvalue = the;Const int* Pconstint = &nValue;///correct, you can assign int * to const int *, but pconstint cannot change the value of the object it points to, that is Nvalue*pconstint = +;//error, cannot change the value of the object it points to
The difference between const int* and int* const

The pointer itself is an object that defines the pointer as a constant, a constant pointer, a type of int* const, or an int *const, which must be initialized when declared.

intNvalue =Ten;int*Constp = &nValue;int*ConstP2 = &nValue;Const int* The object pointed to by the pointer can not be changed, but the value of the pointer itself can be changed;int*ConstThe value of the pointer itself cannot be changed, but the object it points to can be changed.intNValue1 =Ten;intNValue2 = -;int*ConstConstpoint = &nValue1;//constpoint = & nValue2; Error, cannot change the value of the Constpoint itself*constpoint = +;//Correct, can change the object that Constpoint points to, at this time nValue1 =Const intNConstValue1 =5;Const intNConstValue2 = the;Const int* PPoint = &nConstValue1;//*ppoint = 55; Error, cannot change the value of the object that PPoint points toPPoint = &nConstValue2;//Correct, you can change the value of the PPoint pointer itself, at this time ppoint is NConstValue2 object, that is, PPoint is the address of nConstValue2

Const int* const is a constant pointer to a constant object that cannot change the value of the pointer itself, nor can it change the object to which the pointer is pointing.

constint5;constint15;constintconst pPoint = &nConstValue1;//*pPoint  = 55;                    //错误,不能改变pPoint所指向对象的值//pPoint = &nConstValue2;           //错误,不能改变pPoint本身的值
Const t&

A reference to a constant (const), also known as a constant reference, cannot modify its state's object.

int5;constint10;constint& rConstInt = constInt;    //正确,引用及邦定的值都是常量5;                      //错误,不能改变引用所指向的对象

Allows a constant reference to a const object, literal value, or even an expression; The reference type must be the same as the type pointed to by the reference.

inti =5;int& rInt = i;//correct, reference to intConst intConstint =Ten;Const int& rconstint = Constint;//correct, reference and the value of the bond are constantsConst int& rConstInt2 = rInt;//Correct, assign with Rint-Bond objectRInt = -;///At this time, the values of RConstInt2, rInt and I are all//rconstint2 = 30; Error, RConstInt2 is a constant reference, and RConstInt2 itself cannot change the object being pointed tointI2 = the;Const int& rConstInt3 = i2;//Correct, assign a value to the object with a very good amountConst int& rConstInt4 = i + i2;//Correct, assign it with an expression value ofi = -;//At this time i=20, rInt = RCONSTINT4 = 45, indicating that RConstInt4 Pradesh is a temporary variable of i + I2Const int& rConstInt5 = -;//positive solution, assigning a value to it with a constant value
Const t*& with T *const&

A reference to a pointer to a constant object, which can be understood in two steps: 1.const t* is a pointer to a constant, and 2.const t*& a reference to a pointer to a constant.

Const intNconstvalue =1;//Constant ObjectConst intNConstValue2 =2;//Constant ObjectConst int* Pconstvalue = &nConstValue;//Pointer to constant objectConst int* PConstValue2 = &nConstValue2;//Pointer to constant objectConst int*& rpconstvalue = Pconstvalue;//reference to a pointer to a constant object//*rpconstvalue = 10; Error, Rpconstvalue points to a constant object, the value of a constant object cannot be changedRpconstvalue = pConstValue2;//correct, at which point the value of Pconstvalue equals PConstValue2//Pointer to a constant object itself is an object, reference can change the value of a state objectintNvalue =5;intNValue2 =Ten;int*ConstConstpoint = &nValue;//constant pointerint*ConstConstPoint2 = &nValue2;//constant pointerint*Const&rpconstpoint = Constpoint;//reference to a constant pointer, bonding constpoint//rpconstpoint = ConstPoint2; Error, Constpoint is a constant pointer, the value of the pointer itself cannot be changed*rpconstpoint = -;//Correct, the object pointed to by the pointer can be changed
The application in the function

We come directly from the requirements, assuming that there is a data structure:

struct __Data{    intvalue;public:    __Data()        :value(0){}}Data;
1. Want to pass in an object, and not want the function body to modify the object. Way <1>
voidDealwithDatadata){    data.value << endl;    //data.value = 5;       //错误,data是常量引用,不能改变其邦定的对象}

Another benefit of this approach is that it is only when the function is invoked that the object is passed a reference to the object, not the object, which reduces the cost of assigning the object when the function is called.

Way <2>
void Dealwith(const Data* pData){    cout << pData->value << endl;    //pData->value = 5;     //错误,pData是指向常量对象的指针,不能改变其指向的对象}

This is the same as the function of the void Dealwith (const data& Data)

Way <3>
Data g_data(20);voidData*& pData){    << pData-><< endl;    //pData->value = 5;     //错误,pData邦定的是指向常量对象的指针,常量对象的指针不能改变其指向的对象    =&g_data;        //正确,pData是[指向常量对象的指针]的引用,引用可改变其邦定的对象}

The call is as follows:

Data d(10Data*=&<< pData-><< endl;   //此时pData->value为20,d.value还是10

This way the function does not change the value of the incoming object, but it can return a pointer to another object. Note that the returned pointer must point to the global object, which is dangerous if the object defined within the function is returned, and its pointer is invalid after exiting the function scope, which is very risky; if Dealwith is a member function, you can also return a pointer to a member.

2. Used in a class, returns a member of a class, but does not want the caller to modify the member. Way <1>
class MyData{public :    MyData(std::stringDatadata)    {        = name;        =data;    }    Data* GetData()    {        return&m_data;    }private:    std::string m_name;    Data m_data;};

The call is as follows:

MyData mydata(""Data(100Data*= mydata.<< pData-><< endl;   //pData->value = 100//pData->value = 50;            //错误,pData是指向常量对象的指向,不能改变其指向对象的值 
Way <2>

One might ask GetData can also be written like this:

const Data& GetData(){    return m_data;}

In this case, the caller is often easily written like this:

MyData mydata(""Data(100));Datadata = mydata.GetData();   //这会有个赋值的过程,会把mydata.m_data赋给datacoutdata.value << endl;     //data.value = 100data.value = 50;                //正确,data.value=50,但mydata.m_data.value还是100

This will have a result assignment procedure, and if data is a complex class, it will have a large overhead and the effect is the same as in the following way:

Data GetData(){    return m_data;}

Of course, if the caller is using this correctly:

const Data& GetData(){    return m_data;}
MyData mydata(""Data(100));constDatadata = mydata.GetData();    //这会有个赋值的过程,会把mydata.m_data赋给datacoutdata.value << endl;             //data.value = 100//data.value = 50;                      //错误,data是一个对常量的引用,不能改变其邦定的对象

This has a high level of technical capability for callers, and if you are a designer, be sure to make the interface as easy as possible.

Way <3>

If you want to pass in a data for some processing, and then return to the class member m_data after processing, you can do the following:

void DoSomething(const Data*& pData){    ifNULL)    {        // doto: 这里实现你要处理的功能    }    pData = &m_data;}

If you have any doubts and ideas, please give feedback in the comments, your feedback is the best evaluator! Due to my limited skills and skills, if the Ben Boven have errors or shortcomings, please understand and give your valuable advice!


If you have any doubts and ideas, please give feedback in the comments, your feedback is the best evaluator! Due to my limited skills and skills, if the Ben Boven have errors or shortcomings, please understand and give your valuable advice!

The difference between const T, const t*, T *const, const t&, const t*&

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.