RAII with boost boost :: program_options and options_description
Following net's example From this answer , I came up with the following:
int server_port;
auto value_port = new po::typed_value<int>(&server_port); //<-- Really??
value_port->value_name("port");
po::options_description opt_config("Configuation");
opt_config.add_options()("port,P", value_port, "listening port");
This seems to work. However , alarms were raised when explicitly calling new
to create raw pointers in C ++.
So the first thing I tried was using a statically allocated object . (I see no need for dynamically allocated memory here):
auto value_port = po::typed_value<int>(&server_port);
value_port.value_name("port");
po::options_description opt_config("Configuation");
opt_config.add_options()("port,P", &value_port, "listening port");
This gives a runtime error on function exit (when variables are destroyed).
The call stack starts with
-
boost::detail::shared_count::~shared_count() Line 447
and the error is on
-
boost::checked_delete<boost::program_options::value_semantic const >(const boost::program_options::value_semantic * x) Line 34
where is the instruction delete
.
Second, I tried to use (from ): unique_ptr
std
auto value_port = make_unique<po::typed_value<int>>(&server_port);
value_port->value_name("port");
po::options_description opt_config("Configuation");
opt_config.add_options()("port,P", value_port.get(), "listening port");
The story looks like 2 frames this time in the call stack:
-
std::unique_ptr<boost::program_options::typed_value<int,char>,std::default_delete<boost::program_options::typed_value<int,char> > >::~unique_ptr<boost::program_options::typed_value<int,char>,std::default_delete<boost::program_options::typed_value<int,char> > >() Line 1449
-
std::default_delete<boost::program_options::typed_value<int,char> >::operator()(boost::program_options::typed_value<int,char> * _Ptr) Line 1200
again in command a delete
.
So it seems that it is options_description
destroying (the at object) the pointer it got through add_options
and the problem is caused by two destruction on the same object.
Shouldn't this be documented? DoesnΕ£ this go against RAII? The caller creates the object, but it is destroyed by another object, which at some point receives a pointer to it. `
I have used boost_1_56_0
with Visual Sudio 2013
the configuration manager debug x64
.
source to share