How can this be compiled? (remove member of const object)

I would expect an error inside the copy constructor, but this is just fine with MSVC10.

class Test
{
public:
    Test()
    {
        p = new int(0);
    }

    Test(const Test& t)
    {
        delete t.p; // I would expect an error here
    }

    ~Test()
    {
        delete p;
    }

private:
    int* p;
};
+3
source share
4 answers

The problem that you are facing is that you do not change pper se (thus, it premains unchanged because you do not change its value), but you change what ppoints to and thus work at one additional level indirectness. This is possible because deleting the memory associated with the pointer does not change the pointer itself.

, , - , p.

JonH, , , const, , .

+3

. delete ( ). , , , delete , . , (std::cout << static_cast<void*>(p);) , , .

, delete - delete . , ( { const mytype var(args); }), , , . .

+4

, , . , .

t.p, , t . t , .

+2

:

int* const p;

... p. const int* .

void *, ( void * delete, -). , , delete ( , ), void * , . , ; delete dtor .

, const Test& int* p , int* const p, int const* p const int* p.

:

Test::Test(const Test& other)
{
    *other.p = 123; // this is valid
    other.p = NULL; // this is not valid
}

In other words, the address of the pointer is immutable, but the dot is not. I often came across a lot of confusion here regarding the constant of a member function and its effect on data elements that are pointers. Understanding this will give a little understanding regarding one of the reasons why we need a separation between the iterator and const_iterator.

0
source

Source: https://habr.com/ru/post/1751931/


All Articles