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