* C 和 C++ 共通的部分提到前面,各自的部分則放到各自的段落。
* 維護 [[wp>C++]] 中文版面。
* 盡可能只紀錄語言層面知識。
* [[https://stuff.mit.edu/iap/2004/inside-c/index.html|The Secret Life of C++: What your compiler doesn't want you to know (C++ Internals)]]
* [[https://github.com/tibbetts/inside-c|The Secret Life of C++: How C++ Compiles to Assembly]]
* [[http://www.cnblogs.com/miloyip/archive/2010/09/17/behind_cplusplus.html|C++强大背后]]
* [[wp>Evaluation strategy]]
* [[wp>Evaluation_strategy#Call_by_value|Call by value]]: C 只有此種方法。
* In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by copying the value into a new memory region).
* [[wp>Evaluation_strategy#Call_by_reference|Call by reference]]: C++ 另外支援此種方法。C 可以用傳遞指針 (仍為 call by value,value 為位址) 模擬 call by reference 的效果。
* In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value.
* [[http://blog.tinlans.org/2009/11/29/%E5%82%B3-pointer-%E5%B0%B1%E6%98%AF-pass-by-value-%E9%80%99%E4%BB%B6%E4%BA%8B%E6%98%AF%E8%A6%81%E9%87%8D%E8%A4%87%E8%AC%9B%E5%B9%BE%E9%81%8D/|傳 pointer 就是 pass-by-value 這件事是要重複講幾遍]]
* [[http://greenteapress.com/thinkcpp/index.html|How to Think Like a Computer Scientist C++ Version]]
* [[http://www.ituring.com.cn/minibook/61|像计算机科学家一样思考(C++版)]]
====== C++ ======
===== 常見問題 =====
* [[http://stackoverflow.com/questions/5100718/integer-to-hex-string-in-c|Integer to hex string in C++]]
#include
#include
#include
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::uppercase
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
* [[http://stackoverflow.com/questions/2874441/deleting-elements-from-stl-set-while-iterating|Deleting elements from STL set while iterating]]
* [[http://stackoverflow.com/questions/16013545/how-do-i-erase-elements-from-stl-containers|How do I erase elements from STL containers?]]
for (auto it = c.begin(); it != c.end(); /* "it" updated inside loop body */ )
{
if ( erasing_condition(*it) )
{
// Erase the element matching the specified condition
// from the associative container.
it = c.erase(it);
// Note:
// erase() returns an iterator to the element
// that follows the last element removed,
// so we can continue the "for" loop iteration from that position.
}
else
{
// Current element does _not_ satisfy erasing condition,
// so we can just move on to the next element.
++it;
}
}
===== C++0x 概觀 =====
* [[wp>C++0x]]
* [[http://herbsutter.com/elements-of-modern-c-style/|Elements of Modern C++ Style]]
* [[http://channel9.msdn.com/Tags/cppbeyond|C++ and Beyond]]
* [[http://blog.csdn.net/pongba/article/category/158724|《C++0x漫谈》系列]]
* [[http://coolshell.cn/articles/5265.html|C++11 中值得关注的几大变化(详解)]]
* [[http://blogs.msdn.com/b/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx|Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1]]
* [[http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx|Rvalue References: C++0x Features in VC10, Part 2]]
* [[http://thbecker.net/articles/rvalue_references/section_01.html|C++ Rvalue References Explained]]
* [[http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/|The Biggest Changes in C++11]]
* [[http://herbsutter.com/2012/02/08/going-native-sessions-online/|Going Native Sessions Online]]
* [[http://stackoverflow.com/questions/11016220/what-are-inline-namespaces-for|What are inline namespaces for?]]
* [[http://novus.pixnet.net/blog/post/32768909|談 C++11 的 Inline Namespace]]
* [[http://blog.logan.tw/2014/05/c-inline-namespace.html|C++ inline namespace]]
* 相對於 GLIBC 所使用的 [[http://stackoverflow.com/questions/2856438/how-can-i-link-to-a-specific-glibc-version|symbol versioning]] 機制,針對函式庫提供語言層級的版本控制。
====== 基礎 ======
* [[http://jjhou.boolan.com/dissecting%20MFC%202e%20part2.pdf|《深入淺出 MFC》 第2章 C++ 的重要性質]]
- Ch1-2: Programming and "Hello, World!"
- Ch3: Objects, Types, and Values
* 在內存中擺放資料的空間稱為物件 (object),物件有其型別 (type),內存有值 (value)。有名字 (name) 的物件稱之為變數 (variable),可透過其名提取該變數的值。
===== 陣列 =====
* [[http://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm|C++ Multi-dimensional Arrays]]
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
===== 指針 =====
int array[5] = {1, 2, 3, 4, 5};
int *ptr;
ptr = array;
*(ptr + 1) = 7;
*(array + 1) = 7; // 不可做指針運算。
* [[http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm|C++ Pointers]]
* [[http://www.tutorialspoint.com/cplusplus/cpp_pointers_vs_arrays.htm|C++ pointers vs arrays]]
char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
* [[http://www.tutorialspoint.com/cplusplus/cpp_array_of_pointers.htm|C++ array of pointers]]
int *foo() {
static int i;
int i; // 不可。此為堆疊上的位址,隨時間變化。
return &i;
}
* [[http://www.tutorialspoint.com/cplusplus/cpp_return_pointer_from_functions.htm|Return pointer from functions in C++]]
===== 參考 =====
* [[http://www.tutorialspoint.com/cplusplus/cpp_references.htm|C++ References]]
int i;
int &r = i; // 必須要有初值,無法像指針一樣可以有空指針。
void swap(int& a, int& b);
int& foo() {
static int i;
return i;
}
====== 類別 ======
* private: 該變數或函式只能在類別自身內部,或是有用 friend 修飾的外部函式內使用。
* protected: 同上。該變數或函式另外能被子類別使用。
* public: 在本類別物件可見範圍內皆可使用。
* [[http://stackoverflow.com/questions/185844/initializing-private-static-members|Initializing private static members]]
* [[http://stackoverflow.com/questions/3531060/how-to-initialize-a-static-const-member-in-c|How to initialize a static const member in C++?]]
* Overload
* [[http://openhome.cc/Gossip/CppGossip/OverloadedFunction.html|C++ Gossip: 重載函式(Overloaded function)]]
* 同名函式,不同參數個數或是型別。返回型別不同無法重載函式。
class Base {
void foo(int);
void foo(double);
};
void bar(int);
void bar(double);
* Override
* [[http://openhome.cc/Gossip/CppGossip/OverrideMemberFunction.html|C++ Gossip: 成員函式的重新定義]]
* 類別繼承時會出現的用語。
class Base {
// 要做到動態多型,宣告成 virtual。
void foo(int);
};
class Derive : public Base {
void foo(int) { /* do different thing */ }
};
* name hiding
class Base {
public:
virtual void foo(double i) { cout << "Base::foo(double) " << endl; }
};
class Derive : public Base {
public:
// Base::foo 被 Derive:foo 給隱藏。
// using Base::foo;
void foo(complex) { cout << "Derive::foo(complex) " << endl; }
};
int main() {
Derive d;
d.foo(1l); // Derive::foo(complex)
Base* pd = new Derive;
pd->foo(1); // Overload 根據靜態型別進行決議。Base::foo(double)
}
===== 多型 =====
基類別內要定義虛擬函式。用指針或是參考引用虛擬函式。只能用基類指針指向衍生類物件,反之不可。
class Base {
public:
virtual ~Base() {}
virtual void foo(int i = 10) { cout << "Base::foo(int)" << i << endl; }
};
class Derive : public Base {
public:
void foo(int i = 20) { cout << "Derive::foo(int)" << i << endl; }
};
int main() {
Base* pd = new Derive;
pd->foo(); // Derive::foo(int) 10
delete pd; // Base 必須要有 virtual dtor。
}
* [[http://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm|Polymorphism in C++]]
* [[http://openhome.cc/Gossip/CppGossip/VirtualFunction.html|C++ Gossip: 虛擬函式(Virtual function)]]
* 抽象類別 (abstract class)
* [[http://openhome.cc/Gossip/CppGossip/PureVirtualFunction.html|虛擬函式、抽象類別(Abstract class)]]
* 類別內只要有一個純虛擬函式,便是抽象類別。
* 無法創建抽象類別之物件。
* 相對於 abstract class 即為 concrete class。
class Shape {
public:
// 其中定義有一個純虛擬函式,留待子類別實作。
virtual void draw() = 0;
};
* 執行時期型別資訊
* [[http://openhome.cc/Gossip/CppGossip/RTTI.html|C++ Gossip: 執行時期型態資訊(RTTI)]]
* 用 typeid 來取得指標或參考所實際代表的物件,進而存取其原生類別特定的變數和函式。
* [[http://openhome.cc/Gossip/CppGossip/dynamicCast.html|C++ Gossip: 使用 dynamic_cast]]
* [[wp>Object slicing]]
* [[http://www.geeksforgeeks.org/object-slicing-in-c/|Object Slicing in C++]]
===== 容器與迭代 =====
[[Data Structure]]
std::list ilist = {1, 2, 3};
for (auto iter = ilist.begin();
iter != ilist.end(); ++iter)
std::cout << *iter << " ";
===== 自訂 IO =====
struct Entr {
string name;
int number ;
};
ostream& operator<<(ostream& os, const Entry& e)
{
return os << "{\"" << e.name << "\", " << e.number << "\"}";
}
===== 例外處理 =====
int main() {
try {
std::cout << vec.at(3);
}
catch (std::out_of_range& err) {
std::cout << "out of range!\n";
}
}
===== 實用組件 =====
* 資源管理 (Resource Management): memory, lock, socket, thread handle and file handle
* 使用 ctor/dtor 自動取得和釋放資源。[[http://www.cnblogs.com/hsinwang/articles/214663.html|RAII (Resource Acquisition Is Initialization)]]
* [[wp>Smart pointer]]
#include
int main() {
std::unique_ptr p1(new int(5));
std::unique_ptr p2 = p1; // p1 獨占該指針所有權,無法轉移。
std::cout << *p1;
/* 不需要手動 delete */
// delete p1;
}
* Regular Expressions
====== 模板 ======
template
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
template
class Stack {
private:
vector elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};
template
void Stack::push (T const& elem)
{
// append copy of passed element
elems.push_back(elem);
}
* [[http://stackoverflow.com/questions/7182359/template-instantiation-details-of-gcc-and-ms-compilers|Template instantiation details of GCC and MS compilers]]
* [[http://wiki.ifs.hsr.ch/SemProgAnTr/files/yt_template_instantiation_and_concepts_in_clang.pdf|C++ Template Instantiation and Concepts in CLANG]]
===== 模板元編程 =====
相較於傳統編程,元編程 (metaprgramming) 是在編譯時期,由編譯器進行計算。
#include
// 主模板 (primary template)
template < unsigned n >
struct factorial {
// 遞歸實例化模板 factorial,並取得 value 成員當作其值。
// factorial::value 可以看做呼叫函數 factorial(n-1) 並取得返回值 value。
static const unsigned value = n * factorial::value;
};
// 顯式特化模板 (explicit specialization),用來定義終止條件。
template <>
struct factorial<0> {
static const unsigned value = 1;
};
int main() {
// 編譯器在遞歸實例化模板 factorial 的過程中會求得 n! 的值。
std::cout << factorial<6>::value << std::endl; // 6! = 720
}
可被編譯器操縱的值稱為元數據 (meta data),常見的元數據為類型 (type) 和整數常量。為了達到靜態多型,通常會將輸入參數和返回值包裝成類型。如此一來,元函數 f 也可被包裝成類 (元函數類),再當作參數傳遞給元函數 g。元函數 g 被稱為高階元函數 (high-order function),意指元函數 g 可以操縱另一元函數 f。元函數可用來計算數值或是類型,數值會被包裝成類型,至於類型計算通常是用來判別某一類型是否具有某種特性,比如該類型是否為一整數 (int) 或是浮點數 (float)。
元函數是一個內含可被公開訪問的 type 成員的類或是樣板類。
template
struct apply {
typedef int type;
}
元函數類是一個內含可被公開訪問的 apply 元函數的類。
struct plus_f {
template
struct apply {
typedef int type;
}
}
成員名 type 或是 apply 均是約定名稱。如此一來,使用者使用不同的元函數(元函數類)可以直接取用 type (apply)。
元函數轉發 (meta function forwarding) 使得子類可透過公開繼承父類,進而將父類的 type 成員暴露出來。
struct foo
: apply
{}
數值會被包裝成類型,稱之為整型外覆器 (interal wrapper)。
// int a = int_wrapper<1>::value;
template struct int_wrapper {
static int const value = x;
};
元數據不可變 (immutable) 且元函數沒有副作用。利用模板進行元編程,需要知道何謂模板顯式特化和部分特化。
* [[http://kuibyshev.bokee.com/1584716.html|C++ Metaprogramming 和 Boost MPL]]
* [[http://www.boostpro.com/writing/ACCU_MPL_slides.ppt|The BoostMetaprogramming Library]]
* [[http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Beyond/dp/0321227255|C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond]]
* [[http://www.books.com.tw/exep/prod/booksfile.php?item=0010216326|C++設計新思維--泛型編程與設計範式之應用]]
====== 進階 ======
* [[wp>Bit field]]
* [[http://www.geeksforgeeks.org/bit-fields-c/|Bit Fields in C]]
* [[http://stackoverflow.com/questions/1044654/bitfield-manipulation-in-c|Bitfield manipulation in C]]
* [[https://msdn.microsoft.com/en-us/library/ewwyfdbe.aspx|C++ Bit Fields]]
* [[http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001320000000000000000|Low Level Operators and Bit Fields]]
====== 反彙編 ======
透過反彙編可以更清楚背後運作的機制。
* libcpp
* libstdc\+\+-v3
* [[http://gcc.gnu.org/ml/gcc-help/2003-10/msg00268.html|Re: GCC C/C++ runtime library question]]
* [[http://gcc.gnu.org/wiki/Libstdc%2B%2B|The C++ Runtime Library (libstdc++)]]
* [[Assembly]]
* [[GCC]]
* [[Binutils]]
* [[wp>C standard library]]
* [[http://www.gnu.org/software/libc/|GLIBC, the GNU C Library]]
* [[wp>C++ Standard Library]]
* [[http://gcc.gnu.org/libstdc++/|The GNU Standard C++ Library]]
* [[http://libcxx.llvm.org/|"libc++" C++ Standard Library]]
====== 文章 ======
* [[http://www.functionx.com/cpp/keywords/typedef.htm|C++ Keywords: typedef]]
* [[http://davidz25.blogspot.tw/2011/07/writing-c-library-intro-conclusion-and.html|Writing a C library, intro, conclusion and errata]]
* [[http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T]]
* [[http://stackoverflow.com/questions/1863153/why-unsigned-int-0xffffffff-is-equal-to-int-1|why unsigned int 0xFFFFFFFF is equal to int -1?]]
* [[https://functionalcpp.wordpress.com/|Functional C++]]
====== 術語 ======
* [[wb>More C++ Idioms]]
* [[wp>Curiously recurring template pattern]]
* [[wp>Substitution failure is not an error]]
* [[wp>Argument-dependent name lookup]]
* [[wp>Policy-based design]]
* [[http://www.airs.com/blog/archives/518|Executable stack]]
* [[wp>Trampoline_(computers)|Trampoline]]
* [[wp>Opaque data type]]
* [[wp>const-correctness]]
* [[http://www.barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword|How to Use C's volatile Keyword]]
* [[http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/|Combining C’s volatile and const Keywords]]
// Constant Addresses of Hardware Registers
// p_led_reg 是一個 constant 指針,指向一個 volatile uint8_t。
uint8_t volatile * const p_led_reg = (uint8_t *) 0x00080000;
// Read-Only Shared-Memory Buffer
int const volatile comm_flag;
uint8_t const volatile comm_buffer[BUFFER_SIZE];
// Read-Only Hardware Register
uint8_t const volatile * const p_latch_reg = (uint8_t *) 0x10000000;
===== 優化術語 =====
* [[wp>Return value optimization]]
====== 參考書籍 ======
* [[http://www.amazon.com/Gotchas-Avoiding-Common-Problems-Coding/dp/0321125185|C++ Gotchas: Avoiding Common Problems in Coding and Design]]
* [[http://www.amazon.com/Inside-Object-Model-Stanley-Lippman/dp/0201834545/ref=sr_1_1?s=books&ie=UTF8&qid=1318428990&sr=1-1|Inside the C++ Object Model]]
* [[http://www.amazon.com/Generic-Programming-STL-Extending-Standard/dp/0201309564/ref=sr_1_1?s=books&ie=UTF8&qid=1318429030&sr=1-1|Generic Programming and the STL: Using and Extending the C++ Standard Template Library]]
* [[http://www.amazon.com/Exceptional-Engineering-Programming-Problems-Solutions/dp/0201615622/ref=sr_1_1?s=books&ie=UTF8&qid=1318429064&sr=1-1|Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions]]
* [[http://www.amazon.com/More-Exceptional-Engineering-Programming-Solutions/dp/020170434X/ref=sr_1_1?s=books&ie=UTF8&qid=1318429081&sr=1-1|More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions]]
* [[http://www.amazon.com/Templates-Complete-Guide-David-Vandevoorde/dp/0201734842/ref=sr_1_1?s=books&ie=UTF8&qid=1318429140&sr=1-1|C++ Templates: The Complete Guide]]
* [[http://www.stroustrup.com/Programming/|Programming -- Principles and Practice Using C++]]
* [[http://product.china-pub.com/198624|C++反汇编与逆向分析技术揭秘]]