Can anyone help me to understand this "weird" behavior? I was playing around with c++11 after long pause in c++ programming. Why everything works fine until I use auto?
static void printIt(int a,const int *b, const int &c)
{
std::cout << "\nArg1 : " << a << "\nArg2 : " << *b << "\nArg3 : " << c
<< std::endl;
}
int main()
{
int myVar { 0x01 };
const int *pmV { &myVar };
const int &rmV { myVar };
printIt(myVar,pmV,rmV); //OK prints 1,1,1
*(const_cast<int *>(pmV)) = 0x02; //Remove constness from pmV and sets new value
printIt(myVar,pmV,rmV); //OK prints 2,2,2
(const_cast<int &>(rmV)) = 0x03; //Remove constness from rmV and sets new value
printIt(myVar,pmV,rmV); //OK prints 3,3,3
myVar = 0x04;
printIt(myVar,pmV,rmV); //OK prints 4,4,4
//So far so good...
auto a = const_cast<int *>(pmV); //Creates a new variable of type int *
*a = 0x05;
printIt(myVar,a,rmV); //OK prints 5,5,5
auto b = const_cast<int &>(rmV); //Should have the same effect as (const_cast<int &>(rmV)), right???
b = 0x06;
printIt(myVar,a,b); //WRONG!!! prints 5,5,6
}
Can anyone help me? Thanks so much.
Aucun commentaire:
Enregistrer un commentaire