Archived

This topic is now archived and is closed to further replies.

Simple const_cast question

This topic is 5149 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am currently adapting to the new c++ casting operators, but am confused as to why the following doesn''t work as I expect:
void Foo(int& val)   { val++; };
    
const int val = 0;
Foo(const_cast<int&>(val));
After Foo is called, val still has the value of 0, instead of 1. Why?

Share this post


Link to post
Share on other sites
const_cast Operator
C++ Specific

const_cast < type-id > ( expression )

The const_cast operator can be used to remove the const, volatile, and __unaligned attribute(s) from a class.

A pointer to any object type or a pointer to a data member can be explicitly converted to a type that is identical except for the const, volatile, and __unaligned qualifiers. For pointers and references, the result will refer to the original object. For pointers to data members, the result will refer to the same member as the original (uncast) pointer to data member. Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.

The const_cast operator converts a null pointer value to the null pointer value of the destination type

END C++ Specific

------------------------------------------------

Read you compiler documentation!
the const_cast operator is not for that usage.

Try static_cast although dynamic_cast might be more approriate, but I'm not sure if that will work as I have never used it.

Converting an argument val to a reference is not a valid use of cpp runtime casting...er...don't quote me on that ;-)

dynamic_cast Used for conversion of polymorphic types.

static_cast Used for conversion of nonpolymorphic types.

const_cast Used to remove the const, volatile, and __unaligned attributes.

reinterpret_cast Used for simple reinterpretation of bits



[edited by - citizen3019 on November 6, 2003 11:34:22 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You should know that using const_cast operator on an object initially cast as const is undefined and unsafe, which is the manner in which you are using it.

For example:

#include <cstdlib>
#include <iostream>

using namespace std;

void f(const int& i)
{
int& j = const_cast<int&>(i);
j++;
}

int main()
{
const int i = 0;
int j = 0;

// this results in undefined behavior because i
// it was declared const.
f(i);

// this results in defined behavior since j
// was defined as non-const.
f(j);

// undefined value for i
cout << i << endl;

// well-defined value for j
cout << j << endl;

system("PAUSE";
}

Share this post


Link to post
Share on other sites