2014-09-27 21 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爲衆多漂流在互聯網上的人之一