3

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.

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • Destruction is not "changing the object". Else constant object could not exist in automatic storage. You cannot protect your objects from dedicated person. One way to reduce amount of accidental errors is to return non-owning smart pointer (observer_ptr) – Revolver_Ocelot Mar 24 '16 at 17:01
  • Regardinng the second part of your question, the compiler cannot protect against badly written code. If you don't want anyone to modify the internals of a class you need to write the interface correctly using member functions and don't expose member variables. – Tony Mar 24 '16 at 17:04
  • @Tony could you provide an example that works for every situation (for example, when `m_a` can also be `nullptr`)? – nyarlathotep108 Mar 24 '16 at 17:09
  • 1
    If you have to return pointer but need to prevent delete, then hide the destructor. – Manish Baphna Mar 24 '16 at 17:37
  • @nyarlathotep108 - It does not matter if a pointer can be `null` or not. You want it protected from changes outside the class, so don't expose it; `const` is not a panacea. Exposing member variables is a code smell: [Indecent Exposure](http://blog.codinghorror.com/code-smells/). I also answered a [similar question](http://stackoverflow.com/questions/5168981/what-good-are-public-variables-then/5169119#5169119) regarding the use of `get` and `set` methods which may be of interst to you. – Tony Mar 24 '16 at 18:17
  • @ManishBaphna - I'm sorry, but that is awful advice. What you suggest makes it uncler who is responsible for deleting the object. The question does not include enough info the recommend that. If you are constructing objects to give out, use the Fatory pattern. If not, why not return a reference and let the objct be cleaned up by the class that created it. – Tony Mar 24 '16 at 18:20
  • 1
    @Tony Agree, but I didn't want to repeat advice already given here:) My comment was for situation where, for whatsoever reason, someone wants to do the way its' done in question here. For that, class A can hide destructor and allow B to destroy if as B owns it. Also, as nullptr is possible value, not sure reference would work here. – Manish Baphna Mar 27 '16 at 18:29

0 Answers0