Created
May 2, 2013 06:04
-
-
Save mkacky/5500418 to your computer and use it in GitHub Desktop.
test of reference.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <iostream> | |
class Hoge | |
{ | |
protected: | |
int m; | |
Hoge* p; | |
public: | |
Hoge(int x) : m(x), p(this) { } | |
Hoge(const Hoge& h) : m(h.m), p(this) | |
{ | |
std::cout << "コピーコンストラクタが呼ばれた" << std::endl; | |
} | |
int getM() const { return m; } | |
void setM(int x) { m = x; } | |
const Hoge* getAddress() const { return this; } | |
}; | |
int main() | |
{ | |
std::cout << "std::map<int, Hoge> m;" << std::endl; | |
std::map<int, Hoge> m; | |
{ | |
std::cout <<"Hoge h(3);" << std::endl; | |
Hoge h(3); | |
std::cout <<"std::pair<int,Hoge> p(0, h);" << std::endl; | |
std::pair<int,Hoge> p(0, h); | |
std::cout << "m.insert(p);" << std::endl; | |
m.insert(p); | |
} | |
std::cout << "\n========参照を使わないパターン=======" << std::endl; | |
std::cout << "Hoge hoge = m.at(0);" << std::endl; | |
Hoge hoge = m.at(0); | |
std::cout << "hoge.setM(0);" << std::endl; | |
hoge.setM(0); | |
std::cout << "hoge.getM() : " << hoge.getM() << std::endl; | |
std::cout << "m.at(0).getM() : " << m.at(0).getM() << std::endl; | |
std::cout << "hogeのアドレス : " << hoge.getAddress() << std::endl; | |
std::cout << "m.at(0)のアドレス : " << m.at(0).getAddress() << std::endl; | |
std::cout << "\n========参照を使うパターン=======" << std::endl; | |
std::cout <<"Hoge& fuga = m.at(0);" << std::endl; | |
Hoge& fuga = m.at(0); | |
std::cout << "fuga.setM(10);" << std::endl; | |
fuga.setM(10); | |
std::cout << "fuga.getM() : " << fuga.getM() << std::endl; | |
std::cout << "m.at(0).getM() : " << m.at(0).getM() << std::endl; | |
std::cout << "fugaのアドレス : " << fuga.getAddress() << std::endl; | |
std::cout << "m.at(0)のアドレス : " << m.at(0).getAddress() << std::endl; | |
return 0; | |
} | |
// 実行例 | |
// std::map<int, Hoge> m; | |
// Hoge h(3); | |
// std::pair<int,Hoge> p(0, h); | |
// コピーコンストラクタが呼ばれた | |
// m.insert(p); | |
// コピーコンストラクタが呼ばれた | |
// | |
// ========参照を使わないパターン======= | |
// Hoge hoge = m.at(0); | |
// コピーコンストラクタが呼ばれた | |
// hoge.setM(0); | |
// hoge.getM() : 0 | |
// m.at(0).getM() : 3 | |
// hogeのアドレス : 0036FBB0 | |
// m.at(0)のアドレス : 001E4AC0 | |
// | |
// ========参照を使うパターン======= | |
// Hoge& fuga = m.at(0); | |
// fuga.setM(10); | |
// fuga.getM() : 10 | |
// m.at(0).getM() : 10 | |
// fugaのアドレス : 001E4AC0 | |
// m.at(0)のアドレス : 001E4AC0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment