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
。让 :
any & operator=(any rhs)
{
any(rhs).swap(*this);
return *this;
}
这意味着any
另一个。这将建立一个临时any
用rhs
的content
以及swap
它与当前对象,有效地做我们想要什么,但...什么成为这一切的点,如果any
只是系统地构建了一个新的,暂时的any
,它会影响到当前对象的所有分配操作?
在我看来,占位符可以完全删除并且占位符* content; 替换为所有者* content;。
不,由于holder
是模板类,因此无效:
holder * content
你需要写
holder<T> * content
但您不知道T
-(这是重点boost::any
)。因此,您可以为所有holder<T>
类创建一个通用的基类-这就是事实placeholder
。
而且,我不理解任何使用的分配机制。让 :
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句