QVector 要求默认构造函数的原因是什么?
问题描述
我可以看到这些类被视为调用默认构造函数所需的复杂对象:
I can see that that classes are treated as complex objects which are required for calling default constructor:
但不清楚为什么需要在 QVector 的隐藏"区域中构造对象.我的意思是这些对象根本无法访问,那么为什么不只是保留内存而不是真正的对象创建呢?
But it's not clear why is it needed to construct objects in the 'hidden' area of QVector. I mean these objects are not accessible at all, so why not just to reserve the memory instead of the real object creation?
作为一个额外的问题,我想问一下,如果我想要一个非默认可收缩对象数组,我可以安全地将 QVector
QVector<;包装器<T>
?其中 Wrapper
是这样的:
And as a bonus question, I would like to ask, if I want to have an array of non-default-constractible objects, can I safely replace QVector<T>
with QVector<Wrapper<T>
? where Wrapper
is something like that:
推荐答案
很容易让 QVector
为非默认可构造类型 T 工作:
It's easy enough to make the QVector
work for a non-default-constructible type T:
宏需要出现在 MyType
声明之后 - 在头文件(如果有)中,并且必须在命名空间或全局范围内:
The macro needs to be present right after MyType
declaration - in the header file (if any), and it must be in namespace or global scope:
不,包装器不正确.它不会破坏 object
成员.它也不提供移动语义,不保护默认构造等. hack
联合成员不是必需的.联合中的任何内容都不会为您默认构建.
No, the wrapper is not correct. It doesn't destruct the object
member. It also doesn't offer move semantics, doesn't protect from being default-constructed, etc. The hack
union member is not necessary. Nothing in a union will be default-constructed for you.
这是一个更正确的包装器 - 它非常类似于 std::optional
.查看 这里 了解 optional 的细微差别代码>需要:)
Here's a more correct wrapper - it pretty much resembles std::optional
. See here to see how much nuance an optional
needs :)
由于赋值运算符是 ref-qualified,它不允许分配给右值,因此它具有以下不会编译的 IMHO 正属性:
Since the assignment operators are ref-qualified, it disallows assigning to rvalues, so it has the IMHO positive property that the following won't compile:
这篇关于QVector 要求默认构造函数的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!