c++ - 发送智能指针到 protobaf。内存问题

标签 c++ protocol-buffers smart-pointers

我使用 protobuf 作为网络通信的数据格式。

在我的数据模型中有 WrapperMessage,包装器包括子消息 RegistrationRequest 和 InputChecking。

在程序的某处,我创建了一种类型的消息(RegistrationRequest/InputChecking),然后将其传递给函数模板以将其包含在 WrapperMessage 中,然后序列化并发送。

但是我的指针有问题? malloc/new/whatever 检测到堆损坏??我不明白,为什么他不想采取 mes.get() 并在运行时下降..

错误:检测到严重错误 c0000374

我的测试程序的所有代码:

#include "ProtobufDataModels.pb.h"
#include <string>
#include <iostream>
#include <memory>

template <class T>
static void SendProto(T * message);

template <class T>
void SendProto(T * message)
{
    WrapperMessage wm;

    if (std::is_same<T, InputChecking>::value)
    {
        std::shared_ptr<InputChecking> mes(message);

        std::string msg;
        message->SerializeToString(&msg);
        std::cout << msg << std::endl; // all ok

        // set inputChecking mes. to wrapperMessage
        wm.set_allocated_mes_inputchecking(mes.get()); // crash here

    }
    else if (std::is_same<T, RegistrationRequest>::value)
    {
    }

}

int main()
{
    InputChecking * inputChecking = new InputChecking();
    inputChecking->set_login("Jack");

    SendProto(inputChecking);

    std::cin.get();

    return 0;
}

最佳答案

在上面的代码中,您将message 对象的所有权转移给shared_ptr 和protobuf wm 对象。这是不正确的。当到达范围末尾时,它们都删除该对象,第二次删除会导致错误。最简单的修复方法是直接使用 message 指针,根本不创建 shared_ptr

关于c++ - 发送智能指针到 protobaf。内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995025/

相关文章:

c++ - 当返回集合指针时,客户端如何知道是否需要销毁它?

c++ - 为什么在使用 unique_ptr 时没有调用析构函数?

c++ - 从 argv[1] 获取数组的大小并用随机数填充它

c++ - 将类视为一流对象

go - 在 proto 消息中声明一个字段标签

serialization - protobuf数据的存储格式是什么?

c# - .NET 进程外服务器的#import 问题

c++ - 错误 : ‘struct sigevent’ has no member named ‘sigev_notify_thread_id’

python - 使用正确的 .proto 文件时无法在 python 中解析 Protocol Buffer 文件

c++ - 使用自定义删除器 boost scoped_ptr/scoped_array