C ++标准列表和默认可构造类型 [英] C++ standard list and default-constructible types

查看:124
本文介绍了C ++标准列表和默认可构造类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么std::list<T>的单参数构造函数要求T是默认可构造类型?我的意思是以下代码无法编译.

Why is that the single parameter constructor of std::list<T> requires T to be a default-constructible type? I mean the following code does not compile.

struct Foo { // does not have default constructor.
  Foo (int i) {} 
}
int main(void) {
  std::list<Foo> l(10);
}

似乎可以将构造并销毁成语他们已经在std :: vector中完成了,尽管列表类做了更多的记账工作.

It seems possible to use the construct and destroy idioms as they have already done in the std::vector, albeit with more book-keeping the list class.

在相关说明中,为什么列表中没有容量功能?您可以争辩说,这样的功能将预先支付内存分配成本,并在以后消除push_back对象时的开销.至少它将使两个STL序列容器的接口更加一致.

On a related note, why not have the capacity function in list? You can argue that such a function would pay memory allocation cost up-front and eliminate the overhead later on as you push_back objects. At least it will make the interfaces of two STL sequence containers slightly more consistent.

推荐答案

std :: list没有容量功能,因为它没有任何意义.它永远不需要像矢量一样调整大小.它的容量仅受可用内存的限制,这不容易确定.

std::list doesn't have a capacity function because it makes no sense; it never has to resize like a vector does. It's capacity is only limited by the available memory, which is not easily determined.

根据您的要求,我认为您实际上是需要reserve()的.向量是一次性的,因为它(非常)需要这种东西.没有特别要求使所有STL容器之间的所有功能保持一致,尤其是当它们对其他容器没有意义的时候.

From what you asked for, I think you actually want reserve(). That's a one-off for vector because it (badly) needs such a thing; there's no particular requirement to make all functions consistent across all STL containers, especially when they make little sense for others.

您可以使用自定义分配器来实现相同的效果.正如曼努埃尔(Manuel)所建议的那样,请看一下助推器.

You can accomplish the same effect using a custom allocator. As Manuel suggested, look at boost.

这篇关于C ++标准列表和默认可构造类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆