Jon*_*nas 9 c++ vector language-lawyer
如该答案所述std::vector<T>,不能包含const T或带有const-members的类。但是,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
}
Run Code Online (Sandbox Code Playgroud)
错误:使用已删除的函数'foo :: foo()'
注意:'foo :: foo()'被隐式删除,因为默认定义格式不正确:
lub*_*bgr 18
您在这里混合两件事。您得到的错误是由于隐式删除的foo()默认构造函数std::vector::resize(size_type count)调用的:
如果当前大小小于
count,则
1)附加其他默认插入的元素
该std::pair模板有一个默认的构造函数,这就是为什么调用V1.resize成功。如果您也提供一个foo,或通过类初始化允许其隐式生成,例如
struct foo
{
const int first = 42;
int second = 43;
};
Run Code Online (Sandbox Code Playgroud)
然后
std::vector<foo> V2;
V2.resize(3);
Run Code Online (Sandbox Code Playgroud)
会很高兴地编译。不会对双方合作进行的操作std::pair<const int, int>和foo是分配。这不会编译:
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
Run Code Online (Sandbox Code Playgroud)
与无关std::vector,但const在两种情况下都与-qualified数据成员有关。