How to protect class member pointers from unwanted destruction?

Viewed 51

I'm pretty surprised that the following code compiles:

struct A{};

int main()
{
    const A * const a = new A();

    delete a;

    return 0;
}

Why is it possible to destroy objects considered constant? Doesn't this break completely the const-correctness? How am I supposed to protect member pointers? For example:

struct A{};

class B
{
public:

    B() :
        m_a( new A )
    { }

    ~B()
    {
        delete m_a;
    }

    const A * const get_a( ) const
    {
        return m_a;
    }


private:

    A * m_a;
};

int main()
{
    const B b;

    delete b.get_a( );

    return 0;
}

Of course I would not like that the object B is modified by anybody except B itself.

0 Answers
Related