请帮助我理解Boost::Any
Please help me understand Boost::Any
Boost::Any
使用广义基类placehoder
,从该基类派生模板化holder
类。placehoder
提供了一个带有虚拟方法的接口,特别是一个检索any所包含的typeid的方法。然后,any包含一个指向placeholder
的指针。我不明白的是placeholder
的目的和虚拟方法的使用。让any
的这个简化结构(接口的源代码在这里可用):
class any
{
public:
template<typename ValueType>
any(const ValueType & value) : content(new holder<ValueType>>(value)) {}
private:
class placeholder
{
public:
virtual const std::type_info & type_info() const = 0;
};
template<typename ValueType>
class holder : public placeholder
{
public:
holder(const ValueType &value) : held(value) {};
virtual const std::type_info &type_info() const
{
return typeid(ValueType);
}
const value_type held;
};
placeholder *content;
}
在我看来placeholder
可以完全去除,placeholder *content;
可以被holder *content;
取代。
此外,我不理解any
中使用的分配机制。Let:
any & operator=(any rhs)
{
any(rhs).swap(*this);
return *this;
}
它将一个any
连接到另一个。这将用rhs
的content
和swap
构造一个临时any
,有效地完成了我们想要的,但。。。如果any
只是系统地构造一个新的临时any
,并将其影响到所有赋值操作的当前对象,那么这一切的意义何在?
在我看来,占位符可以完全删除,占位符*内容;用持有者*内容代替;。
不,因为holder
是一个模板类,所以这是无效的:
holder * content
你需要写
holder<T> * content
但你不知道T
-(这就是boost::any
的全部意义)。因此,您为所有holder<T>
类创建了一个公共基类,这就是placeholder
此外,我不了解在任何情况下使用的分配机制。Let:
any & operator=(any rhs)
{
any(rhs).swap(*this);
return *this;
}
这就是众所周知的"复制和交换"习语。考虑一下更标准的实现会是什么样子:
any & operator=(const any &rhs)
{
//Watch out for self-assignment.
if(&any==this) return *this;
//Clean out the old data
delete content;
// Update our content
content = rhs.content->clone();
return *this;
}
这复制了复制构造函数中的许多行为。复制和交换习惯用法是消除重复的一种方法。复制由复制构造函数完成,清理由临时析构函数完成。
我确实认为operator=
获得一个副本作为其参数是奇怪的,因为它不接受const引用,然后从该引用创建第二个副本。我本可以预料到:
any & operator=(const any & rhs)
{
any(rhs).swap(*this);
return *this;
}
或
any & operator=(any rhs)
{
rhs.swap(*this);
return *this;
}
- boost::any 如何检查空值/未定义的值
- 在可变参数模板函数中存储参数而不使用 boost::any
- 将动态分配对象传递到 boost::any 构造函数中
- 标准::键映射和/或 boost::any 类型的值的类型检查
- 我如何知道 boost::any 是否包含文字字符串
- “boost::any”和“std::any”之间的区别
- 为什么这种类型的擦除实现(简化的 boost:any)会出现分段错误
- 确实 boost::any / std::any 将小对象存储到位
- C++性能:模板vs boost.any
- 将“ double*”转换为“ boost :: Any*”
- QVariant vs boost::any vs boost::variant
- 正在添加 boost::any in a boost::p roperty_tree 可能
- 无法将Boost.Any对象传递到C++Lua绑定
- 生成 Wt 项目时出错。无法打开包含文件:'boost/any.hpp'
- 在其他模板中使用 Any 类(类似于 boost::any)
- 为什么 boost::any 不保存字符串文字
- 获取 void* 指向 boost::any 内容的指针
- 将 boost::any 转换为 boost::variant 的通用函数
- 如何打印 boost::any 的向量,当我将元素类型存储在另一个字符串向量中时
- 获取指向 boost::any::operator= 的指针