简体   繁体   中英

Swapping void* pointers in C++

I wanted to ask if this kind of swapping implementation would work:

 void swap (void* &a, void* &b ) 
 {    
     void * tmp = a;
     a=b;
     b=tmp;
 }

int main() 
{
   void * a;
   void * b;   
   swap (a,b);
   return 0;
}

Do I need to somehow send the size of the object to the swap method and use it? If so, then what is a good implementation for this function?

Looks fine to me (a pointer is just a pointer, so the sizes of the things it's pointing to doesn't matter), but why not just use std::swap ?

In this example, you're messing with uninitialized variables, which is bad, but that doesn't seem to be the main point of your question.

It works. I'm not sure it does what you think it does: The pointer values are swapped, not whatever they point to.

This function will work just fine for swapping void pointers; the compiler knows their size. If you want to swap something other than void pointers you need a different function.

EDIT: but that's the general pattern for a swap template function:

template <class Ty>
void swap(Ty& lhs, Ty& rhs) {
    Ty tmp = lhs;
    lhs = rhs;
    rhs = tmp;
}

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