作者realmojo (蟹老闆)
看板C_and_CPP
標題[問題] vector初始化的問題
時間Mon Feb 2 12:49:03 2009
#include <vector>
#include <iostream>
using namespace std;
class Bin;
vector<Bin> *v;
struct Bin {
int *glass;
Bin():glass(new int(0)) {}
};
int main() {
v = new vector<Bin>(2);
*(v->at(0).glass) = 9;
cout << *(v->at(1).glass) << endl;
}
為什麼output會是9而不是0?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.91.181
1F:推 chrisdar:請補上 Bin(const Bin& b):glass(new int(0)){} 02/02 13:35
2F:→ chrisdar:Bin(const Bin& b):glass(new int(*b.glass)){} 02/02 13:36
3F:→ realmojo:thanks 02/02 15:49
4F:推 QQ29:請問ch大補上的那個constructor 他是哪時會呼叫呢? 02/02 17:08
5F:推 QQ29:而且為什麼會呼叫~~ 02/02 17:10
6F:推 firose:沒道理阿? 怎麼會這樣?! 02/02 18:01
7F:→ COLDTURNIP:下一篇有寫 XD 02/02 18:07
8F:推 chrisdar:預設建構子 拷貝建構子 指定運算子 三個通常都要補上 02/02 18:57
9F:→ realmojo:下一篇有原因,不過我還是不明白這樣實作的理由 02/02 19:36
10F:→ realmojo:為什麼不幫vector中的每個element呼叫預設建構子 02/02 19:37
11F:→ realmojo:反而是呼叫copy constructor? 02/02 19:39
12F:推 chrisdar:copy constructor 能做的事情比較多阿 XD 02/02 20:08
13F:→ firose:vector(size_type n) Creates a vector with n elements. 02/02 20:12
14F:→ firose:vector(size_type n, const T& t) Creates a vector with n 02/02 20:13
15F:→ firose:copies of t. 02/02 20:13
16F:→ firose:SGI STL 並沒有說會拷貝阿~ 當然看源碼會知道它事實上只有 02/02 20:14
17F:→ firose:合用一個建構式, 第二個參數 t 是預設參數, 但這是實做細節 02/02 20:15
18F:→ firose:真怪~ 究竟是什麼原因呢? 02/02 20:16
19F:推 chrisdar:如果這兩隻函數可以共用的話最理想就是後者包前者的功能 02/02 20:17
20F:推 chrisdar:explicit vector(size_type _Count) 02/02 20:19
21F:→ chrisdar: : _Mybase() {// construct from _Count * _Ty() 02/02 20:19
22F:→ chrisdar: _Construct_n(_Count, _Ty()); 02/02 20:19
23F:→ chrisdar:} 02/02 20:19
24F:→ chrisdar:vector(size_type _Count, const _Ty& _Val) 02/02 20:19
25F:→ chrisdar: : _Mybase() {// construct from _Count * _Val 02/02 20:19
26F:→ chrisdar: _Construct_n(_Count, _Val); 02/02 20:19
27F:→ chrisdar:} 02/02 20:19
28F:推 chrisdar:難道就只是為了程式碼重用?? 02/02 20:21
29F:推 StubbornLin:我也覺得他為啥不呼叫建構子 XD 感覺好像比較合理 02/02 21:00