初始化向量<Temp> myVector(10);
Initialize vector<Temp> myVector(10);
根据 Absolute c++ 书籍:
vector<AClass> records(20); // vector consctructer uses the
// default constructor for AClass to initialize 20 elements.
temp.h
#ifndef TEMP_H
#define TEMP_H
class Temp {
public:
Temp();
static int b;
};
#endif /* TEMP_H */
temp.cpp
#include <iostream>
#include "temp.h"
using namespace std;
int Temp::b=9; // static value for control
Temp::Temp(){
cout<<"Initialize";
++b;
}
main.cpp
#include <iostream>
#include <vector>
#include "temp.h"
using namespace std;
int main(int argc, char** argv) {
vector<Temp> a(10); // 10 elements
cout<<Temp::b;
return 0;
}
我的结果是:
Initialize10;
如您所见,只调用了一次构造函数。为什么会这样?我很困惑。
vector
构造函数在 C++03 和 C++11(及更高版本)中的行为不同。
在 C++03 中,它插入 10 个 default-constructed Temp
对象的副本:默认构造函数被调用一次,复制构造函数(您没有检测)被调用 10次。
在 C++11 中,它插入 10 个 default-constructed Temp
个对象。
根据 Absolute c++ 书籍:
vector<AClass> records(20); // vector consctructer uses the // default constructor for AClass to initialize 20 elements.
temp.h
#ifndef TEMP_H
#define TEMP_H
class Temp {
public:
Temp();
static int b;
};
#endif /* TEMP_H */
temp.cpp
#include <iostream>
#include "temp.h"
using namespace std;
int Temp::b=9; // static value for control
Temp::Temp(){
cout<<"Initialize";
++b;
}
main.cpp
#include <iostream>
#include <vector>
#include "temp.h"
using namespace std;
int main(int argc, char** argv) {
vector<Temp> a(10); // 10 elements
cout<<Temp::b;
return 0;
}
我的结果是:
Initialize10;
如您所见,只调用了一次构造函数。为什么会这样?我很困惑。
vector
构造函数在 C++03 和 C++11(及更高版本)中的行为不同。
在 C++03 中,它插入 10 个 default-constructed Temp
对象的副本:默认构造函数被调用一次,复制构造函数(您没有检测)被调用 10次。
在 C++11 中,它插入 10 个 default-constructed Temp
个对象。