简体   繁体   中英

objective c++ operator delete

I have the following code in Xcode command line app:

#import <Foundation/Foundation.h>

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int main(int argc, const char * argv[])
{
    vector<string> *pv = new vector<string>;
    vector<string> &v = *pv;


    v.push_back("juy");
    v.push_back("zxc");

    cout << v[0] << endl << v[1] << endl;

    delete pv;

    cout << v[0] << endl << v[1] << endl;

    cout << pv->operator[](0) << endl << pv->operator[](1) << endl;
    return 0;
}

When I run it, this is the output:

 juy zxc juy zxc juy zxc 

The question is: does operator delete work in objective-c++? Does it cause memory leak?

There are no errors, no exceptions, nor warnings!

Your code has no memory leaks. However, it has undefined behaviour on the following two lines that come after the delete :

cout << v[0] << endl << v[1] << endl;

cout << pv->operator[](0) << endl << pv->operator[](1) << endl;

In other words, after you delete pv , you are not allowed dereference pv . If your program doesn't crash when you do, and if the memory still contains the old data, that means nothing. The behaviour is still undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM