[英]Why does calling methods on a protobuf Message throw a pure virtual method called error?
I'm trying to use the Google Protobuf library and I want to store a bunch of different message types together in a container and get their names as I pull them out of the container.我正在尝试使用 Google Protobuf 库,我想将一堆不同的消息类型一起存储在一个容器中,并在我将它们从容器中拉出时获取它们的名称。 I think I can use the interface type google::protobuf::Message
to do this.我想我可以使用接口类型google::protobuf::Message
来做到这一点。 Here is what I have so far.这是我到目前为止所拥有的。
#include <iostream>
#include "addressbook.pb.h"
using namespace std;
int main(void) {
vector<shared_ptr<google::protobuf::Message>> vec;
{
tutorial::AddressBook address_book;
vec.push_back(shared_ptr<google::protobuf::Message>(&address_book));
}
cout << "Typename is " << vec.back()->GetTypeName() << endl;
return 0;
}
Calling GetTypeName
throws the following error:调用GetTypeName
会引发以下错误:
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
Note this is me playing around with the tutorial found here:https://developers.google.com/protocol-buffers/docs/cpptutorial请注意,这是我在玩这里的教程:https://developers.google.com/protocol-buffers/docs/cpptutorial
address_book
is on the stack it will be deleted when it goes out of scope, no smart pointer can prevent that. address_book
在堆栈上,当它从 scope 出来时将被删除,没有智能指针可以阻止它。
Just create your book with std::make_shared
, that will be on the heap and its lifetime will be managed from the std::shared_ptr
.只需使用std::make_shared
创建您的书,它将在堆上,其生命周期将由std::shared_ptr
管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.