似乎添加默认构造函数会阻止调用emplace_back并产生错误消息:"静态断言失败:类型不可分配"(gcc 5.3 with -std = c ++ 14).这是一个简单的代码,说明了这个问题:
class A {
public:
int a;
A() = default;
A(int a) {
this->a = a;
}
A(A const & a) = delete;
A& operator =(A const & a) = delete;
A(A && a) = default;
A& operator =(A && a) = default;
};
int main() {
A a(4);
std::vector<A> vec;
vec.emplace_back(std::move(a)); // Error: type is not assignable
return 0;
}
Run Code Online (Sandbox Code Playgroud)
删除默认构造函数时,错误消失了!此外,如果定义了默认构造函数(即使它什么都不做),错误也会消失:
class A {
public:
int a;
A() {
} …Run Code Online (Sandbox Code Playgroud) 使用GCC 6.1.0编译时,以下代码生成分段错误.奇怪的是,错误是一致的,但不会出现较小的尺寸或略微不同的比较表达式.你们有什么想法吗?
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
int n = 1000;
std::vector<std::pair<double, double>> vec;
for(int i = 0; i < n; i++) {
vec.push_back(std::make_pair<double, double>((7*i)%3, (3*i)%5));
}
std::sort(vec.begin(), vec.end(), [](std::pair<double, double> const & p1, std::pair<double, double> const & p2) {return (p1.first < p2.first) || ((p1.first==p2.first)&& (p1.second <= p2.second));});
return 0;
}
Run Code Online (Sandbox Code Playgroud) 似乎某些容器接受std::pair<const int, int>为值类型,但有些容器不接受.问题当然在于该const部分.
我做了一些谷歌搜索,发现只std::vector需要可复制的数据.然而,std::pair<const int, int>工作得很好std::vector,std::set和std::list(也许是其他容器),但没有std::map和std::priority_queue(后者真的很烦我).
以下编译没有问题(gcc 6.1.0)
std::vector<std::pair<const int, int>> vector;
vector.push_back(std::make_pair(3, 5));
std::set<std::pair<const int, int>> set;
set.insert(std::make_pair(3, 5));
std::list<std::pair<const int, int>> list;
list.push_back(std::make_pair(3, 5));
Run Code Online (Sandbox Code Playgroud)
但这会导致编译错误:
std::priority_queue<std::pair<const int, int>> pq;
pq.push(std::make_pair(3, 5));
std::map<int, std::pair<const int, int>> map;
map[2] = std::make_pair(3, 5);
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)error: assignment of read-only member ‘std::pair<const int, int>::first’
这背后的原因是什么?鉴于它们具有相同的底层实现,不应该std::map并且std::set具有相同的行为吗?为什么std::vector它需要移动数据呢?