Being that my C++ isn’t that great, this may be a really simple/obvious answer, but it sure has me stumped. Keep in mind its kinda late here and I’m a little tired. I got this code here:
void TestFunc(int *pVar)
{
cout << endl << *pVar << endl;
delete pVar;
pVar = nullptr;
}
int main(int argc, char *argv[])
{
int *z(new int);
*z = 5;
TestFunc(z);
if (z == nullptr)
cout << "z Successfully Deleted!" << endl;
else cout << "z NOT deleted!" << endl;
return 0;
}
The program compiles just fine with no errors or warning. When I run it, it displays 5, just as I’d expect. However, it says z NOT deleted!. I am curious as to why pVar is not getting set to nullptr even though I explicity set it in my TestFunc() function. Any help would be appreciated. If it matters, this is Visual Studio 2010 and just a regular unmanaged C++ application.
Because it’s being passed by value (i.e. as a copy).
If you want the variable itself to be passed (rather than just its value, which is copied), use
instead.
Note that
deleteonly cares about the pointee, not the pointer. So “deleting” a copy of a pointer deletes the same thing as the original pointer, because in either case you’re deleting their targets, which are the same.