以shared_ptr为参数调用std::move并用等于号时,会调用共享指针的移动构造函数,从而使原共享指针失效:
#include <iostream>
#include <memory>
using namespace std;
int main() {
shared_ptr<int> iptr(new int);
shared_ptr<int> iptr_new = std::move(iptr);
if (!iptr) {
cout << "iptr is invalid" << endl; // 会被输出
}
}
共享指针的移动构造函数相当于做了如下操作:
template<typename T> class shared_ptr {
public:
shared_ptr(shared_ptr &&other) {
ptr_ = other.ptr_;
ref_count_ = other.ref_count_;
other.ptr_ = nullptr;
other.ref_count_ = nullptr;
}
// ...
private:
T* ptr_;
int* ref_count_;
};