C++ 中的用户定义类型和 std::vector

User Defined types and std::vector in C++

我正在尝试用 C++ 创建一个二维点向量。我的问题是在使用 std::vector 存储点之前是否需要为二维点定义复制构造函数、赋值运算符和默认构造函数? 另外,如何为 std 库中定义的向量重载运算符/创建成员函数? 感谢您的帮助:)

My question is whether I need to define the copy constructor, the assignment operator and a default constructor for the 2D point before I use the std::vector to store the points?

来自cppreference

T must meet the requirements of CopyAssignable and CopyConstructible. (until C++11)

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements. (since C++11) (until C++17)

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of Erasable, but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements. (since C++17)

一般来说,是的,您需要一个复制构造函数、一个赋值运算符和一个默认构造函数。但是这些可以隐式提供,这意味着它们将由编译器生成。看看this question就知道在什​​么情况下到底隐式定义了什么。

Also, how do I overload operators/ make member functions for the vector that is defined in the std library?

你不知道。标准库不可修改;充其量,您可以在某些情况下向 std 命名空间添加一些代码,但这不是其中之一。

用户定义的类型总是需要良好的复制语义。即使您没有将它们放入向量中也是如此。将一个对象复制到另一个对象的含义各不相同,但显然有一个要求是这样做不应使程序崩溃。所以真正的问题是您的用户定义类型是否具有良好的复制语义。显然没有看到类型很难说。

如果您有像 struct Point { int x, y; }; 这样的简单类型,那么它已经具有良好的复制语义,您不需要再做任何事情。如果您的 class 包含本身具有良好复制语义的其他对象,则同样适用,因此如果您想在类型中包含 std::string 没有问题,例如struct NamedPoint { std::string name; int x, y; };

通常当 class 必须在析构函数中执行某些操作(例如删除一些内存)时,就会出现问题。然后你需要写一个赋值运算符和复制构造函数。

可以找到更多详细信息 here

PS 您链接的讨论有些混乱。