Vinícius
Vinícius

Reputation: 15746

Deleted heap allocated item evaluates true

struct Set
{
    int a;
    Set() : a(30){};
    bool operator>( const Set& ref ) const
    {
        return ref.a > this->a;
    };
};

int _tmain(int argc, _TCHAR* argv[])
{   
    vector<Set>m_set;
    m_set.push_back( (*(new Set)) );
    cout << m_set.at(0).a;
    delete &(m_set.at(0));
    if( &(m_set.at(0).a) )
        cout << "valid" << endl;

    return 0;
}

Why does it outputs valid, is deleting using this method invalid?

Upvotes: 0

Views: 80

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477110

You never have a reference or pointer to the object which you allocated. The vector will make a copy of the object, but you've lost all track of the original object itself, so there's no way to recover or delete it.

You need to do one of the following:

T * p = new T;
delete p;

T & r = *new T;
delete &r;

Don't use the second version.

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76345

When you access an object that has been deleted the behavior is undefined. Anything can happen.

EDIT: and, more to the point, when you delete an object that wasn't created with new, the behavior is undefined. Anything can happen. That's what the code here does.

Upvotes: 3

Related Questions