2015年5月22日金曜日

コンストラクタ初期化子(C++)

以下のように使用するコンストラクタのコロンは、後ろにメンバ変数や親クラスを初期化する処理を記述することができる。

コンストラクタの中に処理を記述する場合と異なるのは、変数の初期化を省略できることである。

1億回の繰り返し処理で比較した結果、初期化子(コロンを使用した初期化処理)のほうが高速であった(どのくらい高速化は環境によって異なる)。

ただし、プリミティブ型については初期化の必要がないため、初期化子と代入で効率の違いはでないが、記述方法の一貫性やconst対策、コードの可読性のために初期化子を使用するべきである。

 親クラスの初期化についても以下のサンプルに記述しておく。
//
// constructor.cpp
// CplusplusPractice
//
// Created by masai on 2015/05/22.
// Copyright (c) 2015年 masai. All rights reserved.
//
#include <iostream>
#include <chrono>
#include <string>
class constructor_init{
public:
constructor_init() : m_int(0), m_double(.1), m_str("abc"){}
private:
int m_int;
double m_double;
std::string m_str;
};
class constructor_noninit{
public:
constructor_noninit(){
m_int = 0;
m_double = 0;
m_str = "abc";
}
private:
int m_int;
double m_double;
std::string m_str;
};
class parent {
public:
parent(int a){
m_int = a;
}
public:
int m_int;
};
class child : public parent{
public:
child() : parent(2){
}
};
void init(bool constinit){
const auto startTime = std::chrono::system_clock::now();
for(unsigned int i = 0; i < 100000000; ++i){
if(constinit){
constructor_init* c = new constructor_init();
}else{
constructor_noninit* c = new constructor_noninit();
}
}
const auto endTime = std::chrono::system_clock::now();
const auto duration = endTime - startTime;
const auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
std::cout << "duration: " << msec << std::endl;
}
int main(){
// 親クラスの初期化
child* obj = new child();
std:: cout << obj->m_int << std::endl;
// コンストラクタ初期を使用した場合と代入の速度比較
init(true);
init(false);
}
view raw constructor.cpp hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿