【问题标题】:C++ Smart pointers for POCO and Fixtures用于 POCO 和 Fixtures 的 C++ 智能指针
【发布时间】: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


【解决方案1】:

您需要传递智能指针的所有权。

您当前正在使用unique_ptr::get(),它只返回原始指针。

在传递所有权时使用unique_ptr::release(),它返回指针并释放所有权。

在您的代码中:

// object used to set vehicle command 
//    but object is still owned by unique_ptr
set_allocated_vehicle_command(getVehicleCommand_Door().get());

// object is used to set vehicle command
//    and ownership is released from unique_ptr
set_allocated_vehicle_command(getVehicleCommand_Door().release());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多