我正在尝试在类中存储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,这不是我想要的。
答案 0 :(得分: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