以下のコードをビルドして実行すると何が起きるでしょうか?
実際に実行する前に何が起きるか想像して、出力をノートに書いてみてください。
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 <iostream> | |
class Widget { | |
public: | |
explicit Widget(int a, int b) : m_a(a), m_b(b) { | |
std::cout << "construct" << std::endl; | |
} | |
void echo() const { | |
std::cout << m_a << std::endl; | |
} | |
Widget(const Widget &w) : m_a(w.m_a), m_b(w.m_b) { | |
std::cout << "copy construct" << std::endl; | |
} | |
Widget(Widget &&w) : m_a(w.m_a), m_b(w.m_b) { | |
std::cout << "move construct" << std::endl; | |
} | |
Widget &operator=(const Widget &w) = default; | |
Widget &operator=(Widget &&w) = default; | |
private: | |
const int m_a; | |
int m_b; | |
}; | |
Widget func_a(int a) { | |
const Widget w(a, 1); | |
if (a > 0) { | |
return w; | |
} | |
Widget w2(a, -1); | |
return w2; | |
} | |
Widget func_b(int a) { | |
const Widget w(a, 1); | |
return w; | |
} | |
int main(int argc, char **argv) { | |
#ifndef TEST2 | |
const Widget w1 = func_a(1); | |
w1.echo(); | |
const Widget w2 = func_a(-1); | |
w2.echo(); | |
const Widget w3 = func_b(2) | |
w3.echo(); | |
#else | |
Widget w4(1, 2); | |
w4 = func_b(2); | |
w4.echo(); | |
#endif | |
return 0; | |
} |
clangでビルドするなら、
$ clang++ -std=c++11 test.cpp
って感じです。
次に、-DTEST2をつけて
$ clang++ -std=c++11 test.cpp -DTEST2
とするとどうなるでしょうか?
正しく予想出来たらC++を理解していると言ってもいいかもしれません(だめでしょうけど)。
0 件のコメント:
コメントを投稿