我已经使用
该程序的输出结果是:
在这里为什么会调用6次移动构造函数?
g++ -std=c++11 file.cpp
来编译了这个程序,现在我正在学习 C++
中的移动构造函数,但感到有些困惑。#include <iostream>
#include <string>
#include <vector>
using namespace std;
class P {
public:
string* ptr_;
P(string name) { ptr_ = new string(name); }
~P() { delete ptr_; }
P(P&& pother) : ptr_(move(pother.ptr_)) {
cout<<"move"<<endl;
pother.ptr_=nullptr;
}
void print() {cout << *ptr_ << endl;}
};
int main()
{
vector<P> ppl;
ppl.push_back(P("Jojo"));
ppl.push_back(P("Jojo"));
ppl.push_back(P("Jojo"));
}
该程序的输出结果是:
$ ./a.out
move
move
move
move
move
move
在这里为什么会调用6次移动构造函数?
push_back
之前和之后打印出向量的容量和大小,这将有助于理解该主题。 - Benjamin Lindleyptr_(move(pother.ptr_))
实际上不会“移动”任何东西,因为它是一个指针。可以是ptr_(pother.ptr_)
。这并没有错,但指针、整数或任何基本类型都不是使通用引用有趣的东西。 - Eljay