S
S
sharkster2021-11-18 05:54:01
C++ / C#
sharkster, 2021-11-18 05:54:01

How to create a copy of an array of values ​​and an array of pointers without std?

I can't figure out how to make a copy of such a structure:

struct Node {
private:
    int *keys_;
    int min_degree_;
    Node **children_;
    int count_;
    bool is_leaf_;
    ...

Well, it's half clear:

Node(Node const &node) {
    min_degree_ = node.min_degree_;
    is_leaf_ = node.is_leaf_;
    count_ = node.count_;
    ...
}

And how to make a copy without an array of values ​​(int * keys_) and an array of pointers (Node ** children_) without std is not clear. The original object must be deleted, so the links can be copied, although I'm not sure.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-18
@sharkster

To copy an array, you can use memcpy, or do it in a loop.
An array of pointers is no different from an array of values. Simply there values ​​are pointers. Be careful not to make mistakes when using sizeof - if you pass the array itself (pointer) to it, then this will be the size of the pointer, and not the entire array. It is necessary to take the size of one element and multiply by their number.
If the original object can be deleted, then you need to redefine the move operator , not the copy operator. Internally your arrays are just pointers and can be moved around like variables:

keys_ = node.keys_;
node.keys_ = nullptr;

Do not forget to overwrite the original place with a null pointer so that you do not accidentally delete it twice later.
You cannot do this when copying - because you are creating several pointers to the same array and it is generally not clear who should delete it later. Only when moving.
Once you've defined the move operator (or move constructor), then wrap the source element in std::move() when you assign or pass it to the constructor. Then the actual moving method will be called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question