【问题标题】:Please help me understand Boost::Any请帮助我理解 Boost::Any
【发布时间】:2014-11-12 10:36:16
【问题描述】:

Boost::Any 使用通用基类placehoder,从中派生模板化holder 类。 placehoder 提供了一个带有虚方法的接口,特别是一种检索 any 所包含内容的 typeid 的方法。然后 any 包含一个指向 placeholder 的指针。我不明白的是placeholder的用途和虚方法的使用。让这个any 的简化构造(接口的源可用here):

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 分配给另一个。这将构造一个临时的anyrhscontentswap 它与当前对象,有效地做我们想要的但是......如果any 只是系统地,那么这一切的意义就在于构造一个新的临时any 并将其影响到当前对象以进行所有赋值操作?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    在我看来,占位符可以完全删除,占位符 *content; 替换为持有人 *content;。

    不,因为holder 是一个模板类,这是无效的:

    holder * content
    

    你需要写

    holder<T> * content
    

    但你不知道T - (这是boost::any 的重点)。 因此,您可以为所有 holder&lt;T&gt; 类创建一个公共基类 - 这就是 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 2011-05-10
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多