deep copy an object containing fixed length arrays

Hello,
is there a standard way to copy an object for which one or more fields are fixed length arrays?

The object looks like
myStuff.hpp
1
2
3
4
5
6
7
8
9
#define LMAX 101
class myStuff{
private:
double someDouble[LMAX];
double someOtherDouble[LMAX];
int actualSize;
public: 
myStuff();
myStuff& operator= (const myStuff& lhs); 


myStuff.cpp
1
2
3
4
5
// ... some code here ...
myStuff& operator= (const myStuff& lhs){
 // <- what should I put here ??? 
}
// ... some other code here ... 

any tip (included tutorials/standards)?
Last edited on
> is there a standard way to copy an object for which one or more fields are fixed length arrays?

Yes; do not declare these operations. Let the compiler provide the required operations.
Adhere to the rule of zero: http://en.cppreference.com/w/cpp/language/rule_of_three

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

struct A
{
    // implicitly declared copy/move constructors
    // copy/move assignment operators and destructor
    std::string arr1[5] ;
    double arr2[6] {} ; // initialise to all zeroes
};

int main()
{
    A a1 { { "one", "two" }, { 3.4, 5.6, 7.8 } } ;
    std::cout << a1.arr1[0] << ' ' << a1.arr2[1] << '\n' ; // one 5.6

    A a2(a1) ;
    std::cout << a2.arr1[0] << ' ' << a2.arr2[1] << '\n' ; // one 5.6

    a2.arr1[0] = "nine" ;
    a2.arr2[1] = -2.345 ;
    std::cout << a2.arr1[0] << ' ' << a2.arr2[1] << '\n' ; // nine -2.345

    a1 = a2 ;
    std::cout << a1.arr1[0] << ' ' << a1.arr2[1] << '\n' ; // nine -2.345
}

http://coliru.stacked-crooked.com/a/9f1d7e448c89fb27
Do as JLBorges says.

...but if you did have to write your own copy/assignment operator, use the std::copy algorithm to copy the arrays.

1
2
3
4
5
6
7
myStuff& operator= (const myStuff& lhs){
  using std::begin;
  using std::end;
  std::copy( begin(lhs.someDouble), end(lhs.someDouble), begin(someDouble) );
  std::copy( begin(lhs.someOtherDouble), end(lhs.someOtherDouble), begin(someOtherDouble) );
  return *this;
}

Hope this helps.
thanks, that was indeed useful
Topic archived. No new replies allowed.