I’m trying to swap a pointer but all I get is access errors, are there any way to do this?
void Swap(someObject *first, someObject *next)
{
delete first;
first = next;
// I'm guessing this delete first pointer as well ?
delete next;
next = new someObject();
};
Clarification on the method:
It should just swap first with second and create a new instance of “someObject” on second, it shouldn’t swap like = FIRST = SECOND, SECOND = FIRST. Just first becomes second, and second becomes a new object or a new pointer to an object.
Second = Next.
SOLUTION
void Swap(someObject*& first, someObject*& next)
{
std::swap(first, next);
next = new someObject();
};
Try this swap idiom instead. Yours modifies the parameters (and deletes both objects) but does not actually swap the pointer values at the call site.
However, you could just as easily use
std::swapfor this; it will effectively do the same thing this template function does.