作者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