Как глубоко скопировать вариант указателей в C++?C++

Программы на C++. Форум разработчиков
Гость
Как глубоко скопировать вариант указателей в C++?

Сообщение Гость »


У меня есть

Код: Выделить всё

std::variant
whose alternatives are all pointers.

Код: Выделить всё

class a {
public:
int* placeholder;
a(a& _copy) { /* Does a deep copy */ }
}

class b {
// For demonstrational purposes, identical to a.
}

int main() {
std::vector instances = // initialise vector, guaranteed no nullptrs.
}
Now, for instance, if I want to push a deep copy of the first element to the back, I cannot simply do

Код: Выделить всё

instances.push_back(instances[0])
, because that does a shallow copy of the .
Of course, the obvious solution would be to check for all alternatives, then , create a copy, and return the copy. However, I think there has to be a better way. How should something as such be done?
I am also open to solutions that do not use variants.


Источник: https://stackoverflow.com/questions/781 ... nters-in-c

Вернуться в «C++»