请帮助我理解Boost::Any

Please help me understand Boost::Any

本文关键字:Boost Any 帮助      更新时间:2023-10-16

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连接到另一个。这将用rhscontentswap构造一个临时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;
}