Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I use memcpy in C++ to copy classes that have no pointers or virtual functions
    text
    copied!<p>Say I have a class, something like the following;</p> <pre><code>class MyClass { public: MyClass(); int a,b,c; double x,y,z; }; #define PageSize 1000000 MyClass Array1[PageSize],Array2[PageSize]; </code></pre> <p>If my class has not pointers or virtual methods, is it safe to use the following?</p> <pre><code>memcpy(Array1,Array2,PageSize*sizeof(MyClass)); </code></pre> <p>The reason I ask, is that I'm dealing with very large collections of paged data, as decribed <a href="https://stackoverflow.com/questions/2472944/good-c-array-class-for-dealing-with-large-arrays-of-data-in-a-fast-and-memory-e">here</a>, where performance is critical, and memcpy offers significant performance advantages over iterative assignment. I suspect it should be ok, as the 'this' pointer is an implicit parameter rather than anything stored, but are there any other hidden nasties I should be aware of? </p> <p><strong>Edit:</strong> </p> <p>As per sharptooths comments, the data does not include any handles or similar reference information.</p> <p>As per Paul R's comment, I've profiled the code, and avoiding the copy constructor is about 4.5 times faster in this case. Part of the reason here is that my templated array class is somewhat more complex than the simplistic example given, and calls a placement 'new' when allocating memory for types that don't allow shallow copying. This effectively means that the default constructor is called as well as the copy constructor.</p> <p><strong>Second edit</strong></p> <p>It is perhaps worth pointing out that I fully accept that use of memcpy in this way is bad practice and should be avoided in general cases. The specific case in which it is being used is as part of a high performance templated array class, which includes a parameter 'AllowShallowCopying', which will invoke memcpy rather than a copy constructor. This has big performance implications for operations such as removing an element near the start of an array, and paging data in and out of secondary storage. The better theoretical solution would be to convert the class to a simple structure, but given this involves a lot of refactoring of a large code base, avoiding it is not something I'm keen to do.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload