I am using a C library which uses raw pointers from C++. Therefore, I'm looking into wrapping all the pointers to C objects in C++ classes and turning them into smart pointers. I've built a working example:
#include <iostream>
using namespace std;
// the C library is oop: using structs and naming conventions. Like this:
// C library declarations
struct Animal_s {
int age;
};
typedef struct Animal_s Animal;
Animal* make_animal(int age);
void free_animal(Animal* animal);
Animal* do_something_with_animal(Animal* animal);
// C lib implementations
Animal* make_animal(int age ){
auto* animal = (Animal*) malloc(sizeof(Animal));
animal->age = age;
return animal;
}
void free_animal(Animal *animal){
free(animal);
}
Animal* do_something_with_animal(Animal* animal){
//...
return animal;
}
// C++ wrapper
class AnimalWrapper{
Animal* animal_; // how to use smart pointers?
public:
explicit AnimalWrapper(int age){
animal_ = make_animal(age);
};
~AnimalWrapper(){
free_animal(animal_);
}
AnimalWrapper(const AnimalWrapper& animalWrapper){
if (this != &animalWrapper){
animal_ = animalWrapper.animal_;
}
}
AnimalWrapper(AnimalWrapper&& animalWrapper) noexcept {
if (this != &animalWrapper){
animal_ = animalWrapper.animal_;
}
}
AnimalWrapper& operator=(const AnimalWrapper& animalWrapper) {
if (this != &animalWrapper){
animal_ = animalWrapper.animal_;
}
return *this;
}
AnimalWrapper& operator=(AnimalWrapper&& animalWrapper) noexcept {
if (this != &animalWrapper){
animal_ = animalWrapper.animal_;
}
return *this;
}
Animal *getAnimal() const {
return animal_;
}
Animal* doSomethingWithAnimal(){
return do_something_with_animal(animal_);
}
};
int main(){
AnimalWrapper animalWrapper(6);
return 0;
};
This example works and according to valgrind, mangages the memory correctly. However, is it possible to implement the wrapper class using smart pointers? Or must I manually manage the memory in the wrapper classes?