简体   繁体   English

vector_base继承与组合

[英]vector_base inheritance vs composition

Short Question: 简短问题:

Is there a reason why C++ STL implementations use a vector_base struct/class (to handle resources and allocators) as a base class of std::vector rather than using composition ? 有没有理由为什么C ++ STL实现使用vector_base结构/类(处理资源和分配器)作为std::vector基类而不是使用组合

Longer Version: 更长版本:

In my "quest" to improve my knowledge of C++ I've been trying to re-implement a Vector class, mostly std:: compliant. 在我的“追求”中,为了提高我对C ++的了解,我一直在尝试重新实现一个Vector类,主要是std:: compliant。 I think I've understood well enough why is sensible to use allocators and why you'd actually want all the memory handling in a separate class/struct (RAII and all that) but I fail to see why would we want std::vector to inherit from that class rather than having it as a private member. 我想我已经理解为什么使用分配器是明智的,为什么你真的想要在一个单独的类/结构(RAII和所有那些)中的所有内存处理但是我不明白为什么我们想要std::vector从该类继承而不是将其作为私有成员。 LLVM and gcc both use inheritance for example. 例如,LLVMgcc都使用继承。 I find, on the other hand, that constructors and assignments operators (especially the move -types) are much easier to handle using composition. 另一方面,我发现构造函数和赋值运算符(尤其是move -types)使用组合更容易处理。

Am I only exposing my superficial knowledge of the language? 我只是暴露了我对语言的肤浅知识吗?

As an example I searched through some textbook and I found that Stroustroup's books have different versions of his "mock re-implementations" of the standard (just to confuse me more!) with his 2013 book "The C++ Programming language, 4th ed." 作为一个例子,我搜索了一些教科书,我发现Stroustroup的书有他的“模拟重新实现”标准的不同版本(只是为了让我更加困惑!)与他2013年的书“The C ++ Programming language,4th ed。”。 using composition and his 2014 "Programming: Principles and Practice, 2nd ed." 使用作文和他的2014年“编程:原则与实践,第2版”。 using inheritance! 使用继承!

Anyone can help me shed some light? 任何人都可以帮助我解决一些问题?

libc++ uses private inheritance and libstdc++ uses protected inheritance. libc ++使用私有继承,libstdc ++使用受保护的继承。

Protected and private inheritance is largely a syntactic variant of composition . 受保护和私有继承在很大程度上是组合语法变体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM