Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   [help] const_cast (http://www.velocityreviews.com/forums/t275881-help-const_cast.html)

Kaspar Minosiants 07-21-2003 11:29 AM

[help] const_cast
 

Hi ,
there is a question about work of const_cast

The question is why the object is still reachable after a delete operation

class A {
int var;
public:
A():var(0){}
~A(){}
void setVar(int a){var=a;}
int getVar() const {return var;}
int getVar() {return var;}
};
int main() {

const A* a=new A();
A *b=const_cast<A*>(a);
delete a;
b->setVar(10);
cout<<b->getVar();
return 0;
}



Peter van Merkerk 07-21-2003 11:32 AM

Re: [help] const_cast
 
> there is a question about work of const_cast
>
> The question is why the object is still reachable after a delete

operation
>
> class A {
> int var;
> public:
> A():var(0){}
> ~A(){}
> void setVar(int a){var=a;}
> int getVar() const {return var;}
> int getVar() {return var;}
> };
> int main() {
>
> const A* a=new A();
> A *b=const_cast<A*>(a);
> delete a;
> b->setVar(10);
> cout<<b->getVar();
> return 0;
> }


Undefined behaviour, anything might happen. const_cast has nothing to do
with this.
--
Peter van Merkerk
peter.van.merkerk(at)dse.nl



John Harrison 07-21-2003 12:43 PM

Re: [help] const_cast
 

"Kaspar Minosiants" <k-mailnews@yandex.ru> wrote in message
news:bfgiol$eeegs$1@ID-173791.news.uni-berlin.de...
>
> Hi ,
> there is a question about work of const_cast
>
> The question is why the object is still reachable after a delete operation
>
> class A {
> int var;
> public:
> A():var(0){}
> ~A(){}
> void setVar(int a){var=a;}
> int getVar() const {return var;}
> int getVar() {return var;}
> };
> int main() {
>
> const A* a=new A();
> A *b=const_cast<A*>(a);
> delete a;
> b->setVar(10);
> cout<<b->getVar();
> return 0;
> }
>


Well what would you expect to happen? Its not a compile error, so what sort
of error?

The truth is that accessing an object after it has been deleted is an
example of 'undefined behaviour', which means ANYTHING could happen,
including your program 'working'.

This has nothing to do with const_cast.

john




All times are GMT. The time now is 07:26 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.