虽然显式实例化向量< someType&gt ;,什么是someType默认构造函数? [英] While explicitly instantiating vector<someType>, what is the someType default constructor used for?

查看:189
本文介绍了虽然显式实例化向量< someType&gt ;,什么是someType默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C ++ Primer第5版的练习

It's an exercise from C++ Primer 5th Edition:


练习16.26:假设NoDefault是一个类没有
默认构造函数,我们可以显式实例化 vector< NoDefault>
如果不是,为什么不呢? P.677

Exercise 16.26: Assuming NoDefault is a class that does not have a default constructor, can we explicitly instantiate vector<NoDefault>? If not, why not? P.677

我知道如果code> NoDefault 没有默认构造函数,但不能解释原因。任何人都可以告诉我在显式实例化模板类std :: vector< NoDefault> 时使用的默认构造函数如何?

I know it doesn't compile if class NoDefault has no default constructor, but can not explain the reason. Can anyone tell me how is the default constructor used while explicitly instantiating template class std::vector<NoDefault> ?

推荐答案

C ++ 11引入了一个新的构造函数 vector(size_type n)和明显该构造函数不能被实例化,除非 value_type 是默认可构造的。在C ++ 03中是向量(size_type n,const T& = T(),const Allocator& alloc = Allocator())分离构造函数。对 resize()也做了类似的更改。

C++11 introduces a new constructor, vector(size_type n), and "obviously" that constructor can't be instantiated unless the value_type is default-constructible. It was vector(size_type n, const T & = T(), const Allocator& alloc = Allocator()) in C++03, but they changed it to two separate constructors. A similar change was made to resize().

在GCC中, :向量模板可以至少隐式地被实例化而没有元素是默认可构造的。隐式模板类实例化只实例化您使用的成员函数。

In GCC and as far as I know also per the standard: the vector template can be at least implicitly instantiated without the elements being default constructible. Implicit template class instantiation only instantiates the member functions you use.

在C ++ 03中,只有默认参数使用默认构造。您可以显式实例化模板,但是您将无法调用这些函数,而不为该参数提供值。

In C++03 only the default arguments use default construction. You can explicitly instantiate the template, but you won't be able to call those functions without providing a value for that parameter.

所以我很确定变化是什么阻止向量< NoDefault> 在C ++ 11中被显式实例化(我认为allocator类型也需要默认构造)。但我可能错过了一些。看来有点奇怪做出这种变化,因为它引入了这种向后的不兼容性。如果你想要更深层的理由为什么这个不再工作,而不是为什么不工作,可能有一个建议: - )

So I'm pretty sure that change is what prevents vector<NoDefault> being explicitly instantiated in C++11 (and I suppose the allocator type needs to be default-constructible too). But I might have missed something. It seems a little odd to make that change given that it introduces this backward incompatibility. There's probably a proposal somewhere that justifies it if you want a deeper reason why this no longer works as opposed to just why this doesn't work :-)

这篇关于虽然显式实例化向量&lt; someType&gt ;,什么是someType默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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