纯虚拟方法调用错误 Google 协议缓冲区

Pure Virtual Method Called Error Google Protocol Buffer

现在我有一个 QList 的 protobuf 消息。在 while 循环内,我创建消息并将它们添加到 QList。我尝试使用 DebugString 方法将它们打印出来,在 while 循环中它工作正常,没有错误。当我尝试在 while 循环之外调用完全相同的 ->DebugString() 方法时,我得到:

Abort (Core dumped).

pure virtual method called terminate called without an active exception

QList<const ::google::protobuf::Message*> allMessages;

while() {
    msgs::sensor::Plot nextMsg;
    ....
    allMessages.append(&nextMsg);
    std::cout << allMessages.at(0)->DebugString();
}
std::cout << allMessages.at(0)->DebugString();

nextMsg是while循环内的局部变量,跳出循环时销毁,allMessages中保存的地址变为悬空。对它的任何取消引用都只是 UB。

如果你想在循环外使用指针,你需要在循环内new它们(最后delete它们),或者使用smart pointers来避免手动内存管理。