我试图在类中存储boost::program_options::options_description
,但我无法为我的类编写赋值运算符,因为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,这不是我想要的。
因此,这只是意味着options_description
不可复制。要做到这一点,请使其成为shared_ptr
(具有共享所有权语义[1])或具有适当clone
操作[2]的value_ptr
。
基于shared_ptr
的简单演示:在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对于在网络间浮动的许多中的一个