2014-09-27 67 views
2

我试图在类中存储boost::program_options::options_description,但我不能为我的课写assignment operator,因为options_description有一个const成员。或者至少我是这样理解问题的。复制分配助推options_descriptions

这里是我的类的实例,将无法编译:

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,这不是我想要的。

回答

2

所以,这只是意味着options_description是不可复制的。要做到这一点,使其shared_ptr(与共享所有权语义[1])或value_ptr与适当的clone操作[2]。基于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为众多漂流在互联网上的人之一