【问题标题】:Is std::iterator inherints from a sort of auto_ptr?std::iterator 是否继承自某种 auto_ptr?
【发布时间】:2020-10-05 04:38:55
【问题描述】:

我是 STL 的初学者。我正在尝试编写一个 toystl 来学习 STL。当我编写关于迭代器的代码时,我很困惑是否应该先编写一个简单的 auto_ptr 并从中继承。

我写了一个叫做迭代器的基类。现在它是这样工作的,

struct iterator{};

template <class T>
struct vector_itorater: public toystl::iterator<toystl::random_access_iterator_tag, T>{};

如果我需要另一个像“auto_ptr”一样的基类?就这样

// firstly define a sort of auto_ptr as base class
struct auto_ptr{};

// secondly inherint from auto_ptr
template <class T>
struct vector_itorater: public auto_ptr{};

这行得通吗?还是STL是这样做的?

【问题讨论】:

  • 如果您想知道它是如何实现的,只需查看 auto_ptr 的源代码即可。但是,auto_ptr 有一些严重的问题,您应该将 shared_ptr 或 unique_ptr 与更现代的 c++ 一起使用。特别是当您处于学习模式时。最好用最新的 c++ 和一本最新的书来学习。
  • 为什么向量的迭代器会继承自auto_ptr?标准容器的迭代器对它们引用的数据都没有任何所有权。 auto_ptr 在 C++17 中也已弃用和删除,因此即使迭代器确实拥有数据,auto_ptr 也是一个糟糕的选择。
  • 通常情况下,迭代器只需要很少的数据。例如,您可以只用一个指针来实现一个向量迭代器。因此,迭代器通常是按值传递的可复制结构,因此类本身不需要内存管理。
  • @doug 谢谢,我明白了。我正在阅读 Soctt Meyers 的 一书。
  • @Miles Budnek 我最初想重用诸如“*”、“->”和“++”之类的操作。这个好像不行

标签: c++ stl


【解决方案1】:

我认为您混淆了运行时多态性和编译时多态性。当编译器实例化一个模板时,它关心具体对象的可见接口。它不关心这个对象是否与其他类有继承关系,只要具体对象可以在具体上下文中使用,它就会通过。

template <class C>
void foo(const C& bar)
{
    // at the time of writing we don't know anything of C,
    // only that it has a callable baz member (either a
    // member function or a member with a call operator).
    // This works, since the compiler knows the exact type
    // during template instantiation, but we don't have to
    // care in advance.
    bar.baz();
}

struct X
{
    void baz() const;
};

void grml()
{
    X x;
    // The compiler fills in X as the template type
    // parameter for us. So the compiler creates a
    // void foo<X>(const X&) function for us.
    foo(x);
}

在这个例子中,当编译器看到模板时,它不知道以后如何调用这个模板。只有在模板被实例化(使用)后,编译器才会检查传递的类型是否适合该模板。

这里不需要有一个通用的基类来派生每个可能的实现。 STL 使用模板来避免使用此类基类,因为它们会给您以后的设计带来负担,并且如果您在基类中有要覆盖的虚拟成员,您可能会受到严重的性能损失。

【讨论】:

  • 谢谢,模板真的很强大!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多