I am currently trying to wrap my head around on how to properly use C++ smart pointers. I keep reading that I should use make_unique() most of the time, but I always get segfaults with them and I am unsure on how to properly use them.
I am trying to instantiate some Protocol Buffers generated classes for testing purpose. Here's what I am trying to do:
using namespace std;
#include <catch.hpp>
class Fixtures {
public:
std::unique_ptr<DescendingMessage> getDescendingMessage();
std::unique_ptr<VehicleCommand> getVehicleCommand_Door();
std::unique_ptr<Door> getDoorCommand_open();
};
unique_ptr<DescendingMessage> Fixtures::getDescendingMessage() {
auto descendingMessage = make_unique<DescendingMessage>();
descendingMessage->set_allocated_vehicle_command(getVehicleCommand_Door().get());
return move(descendingMessage);
}
unique_ptr<VehicleCommand> Fixtures::getVehicleCommand_Door() {
auto vehicleCommand = make_unique<VehicleCommand>();
vehicleCommand->set_allocated_door_operation(getDoorCommand_open().get());
return move(vehicleCommand);
}
unique_ptr<Door> Fixtures::getDoorCommand_open() {
auto door = make_unique<Door>();
door->set_mode(Door_Mode_OPEN);
return move(door);
}
SCENARIO("Get a sample protobuf model from Fixtures and test its content") {
auto fixtures = make_unique<Fixtures>();
auto descendingMessage = fixtures->getDescendingMessage();
REQUIRE(!descendingMessage->has_metadata());
REQUIRE(!descendingMessage->has_state_request());
REQUIRE(descendingMessage->has_vehicle_command());
}
Whenever I instantiate my Fixtures class in my Catch2 Test, I get a segmentation fault when I try to get an instance of DescendingMessage
. I know it has to do with memory getting freed twice, but I don't know how to properly fix this issue. I tried with shared_ptr and it does the same thing. What am I missing here? I would really like to use smart pointers but I am getting nowhere with them for now :/