简体   繁体   中英

Delete a pointer in cpp and the new operator

May I have to delete a pointer only if i use new ? I tried a code like this :

std::vector<float>* intersections;

    intersections=&KIN_Trigonometry::getIntersectionCircleAndLine( xA, yA, xB, yB, x, y, radius * 2, nbPoints);

    delete intersections;

it give me Assertion failure ... I already used delete with a pointer when I was using new like

int* p = new int[2];
delete p;

Thanks for your support

In the case of your example code int* p = new int[2]; delete p; int* p = new int[2]; delete p; , you created a new array, so you should use delete[] rather than delete

See cplusplus reference: operator delete[]

Meanwhile, I realize you're asking about the code block above that. Since you are not allocating the object with operator new then you should not be using operator delete nor operator delete[] to deallocate it. That is your problem.

Chances are, you probably want to use free() to deallocate this object, if you are to deallocate it at all. You will want to check the code or its documentation to be sure.

Based on the fact that you're taking the address of the function's return value, I don't think you should ever be deallocating this yourself at all.

note the 'intersection = &....' You are taking the address of the return value, that doesnt make you the owner of it.

I suspect you should be doing

std::vector<float> & intersections=KIN_Trigonometry::getIntersectionCircleAndLine( xA, yA, xB, yB, x, y, radius * 2, nbPoints);

or maybe

std::vector<float>  intersections=KIN_Trigonometry::getIntersectionCircleAndLine( xA, yA, xB, yB, x, y, radius * 2, nbPoints);

you have to check the signature of the get function

You can't delete intersections in your first statement because intersections (as far as we can see here) has no allocated space, it's just a link to an adress. So you have to allocate a memory space to intersections using new and then delete this memory space.

This code should not even compile.

intersections = &KIN_Trigonometry::getIntersectionCircleAndLine(...);

Tries to take an address of a returned temporary, and this is prohibited. You are either compiling the code with the Very Bad Compiler, or you are not giving us the real code.

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