提问人:John 提问时间:5/2/2022 更新时间:5/2/2022 访问量:44
为什么无法初始化“std::vector”?[复制]
Why the `std::vector` could not be initialised? [duplicate]
问:
下面是代码片段:
#include <iostream>
#include <vector>
template <typename T>
class Point
{
public:
Point() = default;
Point(T x, T y):x_(x),y_(y){}
//Point(const Point&) = delete;
Point(Point&&) = default;
T x_;
T y_;
};
#define INIT_VECTOR
int main ()
{
#ifdef INIT_VECTOR
std::vector<Point<int>> myvector={{1,1},{2,2}}; //why it does not compile?
#else
std::vector<Point<int>> myvector; //whereas, this works well.
myvector.reserve(5);
#endif
myvector.emplace_back();
auto& point = myvector.back();
point.x_ = 6;
point.y_ = 9;
std::cout << "myvector contains:" << std::endl;
for (auto& pt: myvector)
{
std::cout << ' ' << pt.x_ << "," << pt.y_ << std::endl;
}
return 0;
}
很明显,它没有复制构造函数,而它有移动构造函数。
我的问题是为什么不编译?
有人可以澄清一下这件事吗?我想了又想,但还是想不通为什么。Point<T>
std::vector<Point<int>> myvector={{1,1},{2,2}};
答: 暂无答案
评论
Point(T x, T y):x_(std::move(x)),y_(std::move(y)){}
T
int
mpz_class
vector
initializer_list
const
vector
x_(std::move(x)), y_(std::move(y)
T
x_(x), y_(y)
T
x
y
std::move