1
我被預期用意外行爲::運算=在C++
v2 = v1
V1的內容被複制到V2。
我的經驗是,v1的內容是而不是複製到v2中,如果v1的內容未在構造函數中初始化。
只是看到代碼:
#include <iostream>
#include <vector>
using namespace std;
int main (void) {
vector<int> v1; // if I use vector<int> v1(10,0); it just works fine
vector<int> v2;
v1.reserve(5);
v2.reserve(5);
for (int i = 0; i < 5; i++) v1[i] = i*i;
v2 = v1;
for (int i = 0; i < 5; i++) {
cout << "v1[" << i << "] = " << v1[i] << endl;
cout << "v2[" << i << "] = " << v2[i] << endl;
}
return 0;
}
執行的結果是:
v1[0] = 0
v2[0] = 0
v1[1] = 1
v2[1] = 0
v1[2] = 4
v2[2] = 0
v1[3] = 9
v2[3] = 0
v1[4] = 16
v2[4] = 0
爲什麼這種奇怪的行爲?