Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying assigning boost options_descriptions

Tags:

c++

boost

I'm trying to store a boost::program_options::options_description in a class, but I can't write an assignment operator for my class because options_description has a const member. Or at least that's how I understand the problem.

Here's an example of my class that won't compile:

struct command
{
    command()
    {
    }

    command(const std::string& name,
            const po::options_description& desc)
        : name(name), desc(desc)
    {
    }

    command& operator=(const command& other)
    {
        name = other.name;
        desc = other.desc; // problem here
        return *this;
    }

    ~command()
    {
    }

    std::string name;
    po::options_description desc;
};

/usr/include/boost/program_options/options_description.hpp:173:38: 
error: non-static const member 
‘const unsigned int boost::program_options::options_description::m_line_length’, 
can’t use default assignment operator

/usr/include/boost/program_options/options_description.hpp:173:38: 
error: non-static const member 
‘const unsigned int boost::program_options::options_description::m_min_description_length’, 
can’t use default assignment operator

Originally this was a self-answered question. Then I realized that:

command& operator=(const command& other)
{
    name = other.name;
    desc.add(other.desc);
    return *this;
}

will append other.desc to desc, which is not what I want.

like image 986
user4085715 Avatar asked Jan 19 '26 11:01

user4085715


1 Answers

So, this simply means options_description is not copyable. To make it so, make it either a shared_ptr (with shared ownership semantics[1]) or a value_ptr with appropriate clone operation[2].

Simple demo based on shared_ptr: Live On Coliru

#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

namespace po = boost::program_options;

struct command {
    command(const std::string& name = {},
            const po::options_description& desc = {})
        : name(name), 
          desc(boost::make_shared<po::options_description>(desc))
    {
    }

    command& operator=(const command& other) = default;
  private:
    std::string name;
    boost::shared_ptr<po::options_description> desc;
};

int main() {
    command a, b;
    b = a;
}

[1] options_description already uses these internally, so it's not like you would suddenly incur a large overhead

[2] see e.g. http://www.mr-edd.co.uk/code/value_ptr for one of many floating around on the interwebs

like image 133
sehe Avatar answered Jan 22 '26 00:01

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!