|
-
April 8th, 2013, 11:13 AM
#3
Re: Cloning an object
 Originally Posted by ninja9578
There sure is, but it's not pretty.
Code:
foobar * myobject = new foobar();
foobar * clone = new foobar(); //allocate the space for it, don't use malloc
memcpy(clone, myobject, sizeof(foobar));
You are now 100% assured that clone is exactly the same as myobject.
The above is not guaranteed to give you a valid clone object. If all the members in foobar() are trivial then yes. If any of them have constructors or destructors, the above could be an application crash (or worse) waiting to happen.
Note that in the case that the above would be safe, the compiler is capable of automagically creating a copy constructor for you. making your 2nd approach possible even without explicitely writing it. If the compiler can't make the copy constructor (and you don't want to), the above code is "a really bad idea".
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|