0
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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vinícius
  • 15,498
  • 3
  • 29
  • 53
  • 3
    See here: http://stackoverflow.com/questions/8839943/why-does-the-use-of-new-cause-memory-leaks/8840302#8840302. (Basically, this is undefined behaviour, because you're deleting the wrong object). – R. Martinho Fernandes Oct 30 '12 at 15:25
  • if `B object2 = *(new B());` is impossible to delete, why is it allowed? – Vinícius Oct 30 '12 at 15:30
  • Why would anyone do it? There's little value in forbidding all the really rare useless things people can come up with. No one would write this unless they didn't understand basic C++ concepts, like value semantics. – R. Martinho Fernandes Oct 30 '12 at 15:35

2 Answers2

3

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • In this case the UB is happening at the `delete` statement, because he's deleting a copy of the allocated object. – Praetorian Oct 30 '12 at 15:34
  • @Praetorian - thanks; I missed that. The object created with new is being copied into the vector. Answer edited accordingly. – Pete Becker Oct 30 '12 at 15:38
1

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084