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

Sending smart pointer to protobaf. Memory issue

我使用 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