Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mkacky
Last active December 16, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkacky/5495624 to your computer and use it in GitHub Desktop.
Save mkacky/5495624 to your computer and use it in GitHub Desktop.
test of vector with a stack variable.
#include <vector>
#include <iostream>
class Hoge
{
protected:
int m;
Hoge* p;
public:
Hoge(int x)
:m(x),
p(this)
{
std::cout << "--Hoge(int)--" << std::endl;
std::cout << "コンストラクタの呼び出し" << std::endl;
std::cout << "本オブジェクトのアドレス" << this << std::endl;
std::cout << "---" << std::endl;
}
Hoge(const Hoge& hoge)
:m(hoge.m),
p(this)
{
std::cout << "--Hoge(const Hoge&)--" << std::endl;
std::cout << "コピーコンストラクタの呼び出し" << std::endl;
std::cout << "コピーされるオブジェクトのアドレス" << hoge.p << std::endl;
std::cout << "新たに作成された本オブジェクトのアドレス" << this << std::endl;
std::cout << "---" << std::endl;
}
~Hoge()
{
std::cout << "--~Hoge()--" << std::endl;
std::cout << "デストラクタの呼び出し" << std::endl;
std::cout << "本オブジェクトのアドレス" << this << std::endl;
std::cout << "---" << std::endl;
}
int getM(void) const { return m; }
};
int main()
{
std::vector<Hoge> v;
{
std::cout << "Hoge h(3)でHogeインスタンスを作成" << std::endl;
Hoge h(3);
std::cout << "作成したインスタンスのアドレス" << &h << std::endl;
std::cout << "v.push_back(h)でHogeオブジェクトをvectorに格納" << std::endl;
v.push_back(h);
std::cout << "格納されたインスタンスのアドレス" << &v[0] << std::endl;
std::cout << "ココでスコープを抜ける" << std::endl;
}
std::cout << "格納されたインスタンスのアドレス" << &v[0] << std::endl;
std::cout << "v[0]のmの値 : " << v[0].getM() << std::endl;
// 実行結果(例)
// Hoge h(3)でHogeインスタンスを作成
// コンストラクタの呼び出し
// 本オブジェクトのアドレス0045F8E0
// 作成したインスタンスのアドレス0045F8E0
// v.push_back(h)でHogeオブジェクトをvectorに格納
// コピーコンストラクタの呼び出し
// 本オブジェクトのアドレス009B4FE8
// 格納されたインスタンスのアドレス009B4FE8
// v[0]のmの値 : 3
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment