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. I think I can use the interface type google::protobuf::Message
to do this. 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:
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
address_book
is on the stack it will be deleted when it goes out of scope, no smart pointer can prevent that.
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
.
{
auto address_book = shared_ptr<google::protobuf::Message>(new tutorial::AddressBook);
vec.push_back(address_book);
}