【发布时间】:2018-04-05 18:47:12
【问题描述】:
我目前正在努力思考如何正确使用 C++ 智能指针。我一直在读到我应该在大多数情况下使用 make_unique(),但我总是遇到它们的段错误,我不确定如何正确使用它们。
我正在尝试实例化一些 Protocol Buffers 生成的类以用于测试目的。这是我想要做的:
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());
}
每当我在 Catch2 测试中实例化我的 Fixtures 类时,当我尝试获取 DescendingMessage 的实例时都会遇到分段错误。我知道这与两次释放内存有关,但我不知道如何正确解决此问题。我尝试使用 shared_ptr 并且它做同样的事情。我在这里想念什么?我真的很想使用智能指针,但我现在无处可去:/
【问题讨论】:
-
提供的代码无法编译 - 请提供真实的minimal reproducible example
-
用我的真实代码而不是伪代码更新了上面的代码
-
这仍然不符合minimal reproducible example 的标准 - 我们无法编译此代码并亲自查看。尽管
getVehicleCommand_Door().get()向我表明您在这里传递原始指针,这些指针指向之后立即被销毁的对象 -
哦,我明白了,对不起,我不习惯在这里提问:/ 基本模型是协议缓冲区模型,在这里发布会非常大。我会找到方法签名
-
在这种情况下(基于函数的名称),您将在类中存储悬空指针 - 为什么不让函数本身接受
unique_ptrs(并将unique_ptrs 存储为类成员)?
标签: c++ smart-pointers fixtures