Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
S

Scott K

@Scott K
About
Posts
1
Topics
0
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Generic C++ object/structure swap
    S Scott K

    Thanks, but my question was about swaping the contents of two objects. You are talking about copying an object - very different things. Using your example here is how you would manually swap the contents of two objects: class Stuff { Stuff(); ~Stuff(); void swap(Stuff &rhs): // Swap two objects int number; char *string; }; Stuff::Stuff() : number(0), string(new char[10]) { strcpy(string,"Stuff"); } Stuff::~Stuff() { delete []string; } void swap(Stuff &rhs) { int tmpNumber = number; number = rhs.number; rhs.number = tmpNumber; char *tmpString = string; string = rhs.string; rhs.string = tmpString; } This will work 100% of the time if the object can guarantee that it manages the allocation and destruction of the string memory. The code will obviuosly fail if the user somehow was able to assign stack allocated memory to the string pointer. In that case the Stuff destructor would try to delete a reference to stack memory - very bad thing to do. My question then boils down to why would not the following swap code not work? void swap(Stuff &rhs) { char tmp[sizeof(*this)]; memcpy((void *)tmp, (void *)this, sizeof(*this)); memcpy((void *)this, (void *)&rhs, sizeof(*this)); memcpy((void *)&rhs, (void *)tmp, sizeof(*this)); }

    C / C++ / MFC c++ question data-structures performance
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups