-2

When using memcopy does it just copy the objects in the array or does it copy the memory address of the object and place it in the new array?

If not is there a way to copy the address of objects in array?

Below are the array definitions:

private:
Node<T>* m_data;
long     m_size; 
bool     m_asc; 
Node<T>* m_curr;

I have a method that inserts into m_data, but sometimes m_data needs to be expanded and thus copied over to a temporary array. The problem with that is that in the Node class definition (shown below) connects between successive elements in an array by saving their pointer. If I copy the elements of one list to another it changes their memory address, which results in changes using the pointers not being reflected in the elements of the array. Is there a way to resolve this?

Node<T>* m_next; // pointer to successor element. 
Node<T>* m_prev; // pointer to predecessor element.
  • Are you referring to [`std::memcpy`](http://en.cppreference.com/w/cpp/string/byte/memcpy)? – Fred Larson Apr 09 '18 at 17:54
  • 7
    using `memcpy` with non-POD C++ classes is risky at best (and more often than not just straight up broken) – UnholySheep Apr 09 '18 at 17:55
  • Usually, if you maintain a list structure, you don't store the elements in an array. Instead, you create them with `new`, and later they are only accessible by traversing the list. Otherwise, you have to solve the problem you stated. So, is there a chance that, instead of solving it, you just don't need the array access, and will be fine with only list access? – Gassa Apr 09 '18 at 17:57
  • Useful keywords: `std::copy`, Copy constructor, Rule of Three. – user4581301 Apr 09 '18 at 18:06
  • 2
    `memcpy` copies **bytes**. C++ beginners should not use it. – Pete Becker Apr 09 '18 at 18:08

1 Answers1

1

Historically, memcpy() was intended to copy memory blocks only, without any assumption "what are that content bytes should be by nature". So, rule of thumb:

  • Plain old data (aka POD) can be copied via memcpy. However, it doesn't mean you're obliged to go that way only - STL containers would serve your needs too (and may be way better choice for beginners).
  • In any other case, you have to use STL containers like std::vector or so. Otherwise, you're asking for trouble.
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42