考个研真的把很多东西都忘光了,,,
#include <string_view> #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; class SampleClass { public: SampleClass() { cout << "constructor called" << endl; resource = (int *)std::malloc(sizeof(int) * 100000); } SampleClass(const SampleClass &rhs) { cout << "copy constructor called" << endl; resource = (int *)std::malloc(sizeof(int) * 100000); //memcpy } void swap(SampleClass &lhs, SampleClass &rhs) noexcept { using std::swap; swap(lhs.resource, rhs.resource); } SampleClass(SampleClass &&rhs) { cout << "move contrustor called" << endl; this->resource = rhs.resource; rhs.resource = nullptr; } SampleClass &operator=(SampleClass rhs) { cout << "operator = called" << endl; if (this == &rhs) return *this; swap(*this, rhs); return *this; } ~SampleClass() { cout << "destroyer called" << endl; if (resource != nullptr) { std::free(resource); } } private: int *resource; }; int main(int argc, char **argv) { vector<SampleClass> vec; cout << "first push" << "capacity: " << vec.capacity() << endl; vec.push_back(SampleClass()); //将这个临时对象以右值构造vec中的对象 cout << "second push" << "capacity: " << vec.capacity() << endl; vec.push_back(SampleClass()); cout << "emplace_back" << "capacity: " << vec.capacity() << endl; vec.emplace_back(); cout << "resize" << "capacity: " << vec.capacity() << endl; vec.resize(3); SampleClass a; SampleClass b; cout << "assignment" << endl; a = b; cout << "leave main" << endl; return 0; }
Mingw的输出: