Вопрос

My class contains a unique pointer to an array. When the copy constructor is called, I want the class to create its own unique pointer array and just copy the contents of the old unique pointer array. I keep getting errors about converting from a const value, and I'm not sure how to get around it.

My pointer is declared under private like this:

std::unique_ptr<Manager[]> managers;

I planned to just loop through the array and copy manually, so I made this copy constructor:

Restaurant::Restaurant(const Restaurant &_r)
{
    Manager *_managers = _r.managers;
    for (int i = 0; i < MAX_MANAGERS; i++)
    {
        managers.get()[i] = _managers[i];
    }
}

It gives the const convert error on this line:

Manager *_managers = _r.managers;

I just want to make a deep copy. How can I go about it to make this work?

Это было полезно?

Решение

The reason that it won't compile is that _r.managers is of type std::unique_ptr<Manager[]>, but you want to initialize a raw pointer with this.

just change it to:

Restaurant::Restaurant(const Restaurant &_r)
{
    for (int i = 0; i < MAX_MANAGERS; i++)
    {
        managers.get()[i] = _r.managers.get()[i];
    }
}

or first take a smart pointer's data (which is an array)

Manager *_managers = _r.managers.get();

and then you can use it as was before:

for (int i = 0; i < MAX_MANAGERS; i++) {
        managers.get()[i] = _managers[i];
}

Другие советы

In the line giving you an error, managers is an std::unique_ptr<Manager[]>. You're trying to assign it to a Manager*, which won't work.

You can fix it by taking the raw pointer of of the unique_ptr, for example:

Manager *_managers = _r.managers.get();

In order to copy the content of unique_ptr<>, you might want to use "deep copy", this means that you write copy constructor in class Manager and a clone function. Example for copy constructor:

Manager(Manager const& manager) {
  name = manager.name;
  title = manager.title;
}

clone function:

unique_ptr<Manager> clone() const {
  return make_unique<Manager>(*this);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top