【问题标题】:Copying assigning boost options_descriptions复制分配提升 options_descriptions
【发布时间】:2014-09-27 10:55:27
【问题描述】:

我正在尝试将boost::program_options::options_description 存储在一个类中,但我不能为我的类写一个assignment operator,因为options_description 有一个const 成员。或者至少我是这样理解问题的。

这是我的类无法编译的示例:

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

最初这是一个自我回答的问题。然后我意识到:

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

会将 other.desc 附加到 desc,这不是我想要的。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    所以,这仅仅意味着options_description 是不可复制的。为此,请将其设为shared_ptr(具有共享所有权语义[1])或具有适当clone 操作[2]value_ptr

    基于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 已经在内部使用了这些,所以你不会突然产生很大的开销

    [2] 参见例如http://www.mr-edd.co.uk/code/value_ptr 是互联网上的众多漂浮物之一

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多