[help] const_cast

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kaspar Minosiants

    [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

    #2
    Re: [help] const_cast

    > there is a question about work of const_cast[color=blue]
    >
    > The question is why the object is still reachable after a delete[/color]
    operation[color=blue]
    >
    > 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;
    > }[/color]

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


    Comment

    • John Harrison

      #3
      Re: [help] const_cast


      "Kaspar Minosiants" <k-mailnews@yandex .ru> wrote in message
      news:bfgiol$eee gs$1@ID-173791.news.uni-berlin.de...[color=blue]
      >
      > 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;
      > }
      >[/color]

      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


      Comment

      Working...