【问题标题】:Vector of pair with const member带有 const 成员的对向量
【发布时间】:2019-03-18 09:46:56
【问题描述】:

this answer 中所述,std::vector<T> 不能包含const T,或具有const 成员的类。但是T = std::pair<const int, int>的时候就不是这样了,如下图。为什么会这样? std::pair有什么特别之处?

#include <utility>
#include <vector>

struct foo
{
    const int first;
    int second;
};

int main() {
    std::vector<std::pair<const int, int>> V1;
    V1.resize(3); // This compiles

    std::vector<foo> V2;
    V2.resize(3); // This gives the error listed below
}

错误:使用已删除的函数 'foo::foo()'

注意:'foo::foo()' 被隐式删除,因为默认定义格式不正确:

【问题讨论】:

  • 您链接到关于 C++03 的问答。并不是说它一定无关紧要,但从那以后 C++ 标准中进行了很多调整。

标签: c++ vector language-lawyer


【解决方案1】:

你在这里混合了两件事。您得到的错误是由于std::vector::resize(size_type count) 调用的隐式删除的foo() 默认构造函数:

如果当前大小小于count,
1) 附加了额外的默认插入元素

std::pair 模板有一个默认构造函数,这就是对V1.resize 的调用成功的原因。如果您也为foo 提供一个,或者允许通过在类初始化中隐式生成它,例如

struct foo
{
    const int first = 42;
    int second = 43;
};

然后

std::vector<foo> V2;
V2.resize(3);

将愉快地编译。对std::pair&lt;const int, int&gt;foo 都不起作用的操作是assignment。这不会编译:

V1[0] = std::pair<const int, int>(42, 43); // No way
V2[0] = { 42, 43 }; // Also not ok, can't assign to const data member

这与std::vector 没有任何关系,但在这两种情况下都与const 限定的数据成员有关。

【讨论】:

  • 这不是也与在 C++03 中(OP 引用的问答)中的要求是容器范围的,而现在它们更多地是特定于成员函数的事实有关吗?
  • @StoryTeller 好问题。比较标准的两个版本之间的容器要求似乎有点高于我的工资等级,但我会尝试考虑一下:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多