03 C++: C++ Modern Notes
Initializer list for vector and constructor
C(const initializer_list<int>& v) {}
C v ={1,2,3}
C v{1,2,3}
Extend aggregate initialization to uniform initialization
C++03
Struct S { int a; int b; }; S s = {1,2}
C++11
Class C { C(int a, int b) {} }; C c = {1,2}
Uniform initialization order:
- Initializer_list constructor
- Regular constructor for arguments
- Aggregate initializer for data members
Class C { public:
C(const initializer_list<int>& first);
C(int second);
int third;
}
C c{1};
Auto type
auto x = v.begin(), 1, 2.1, y
foreach
for (int i: v), for (int& i: v)
nullptr replaces NULL
so f(nullptr) must call void f(char*) not void f(int), hence no ambiguity
enum class
enum class side {buy, sell};
enum class answer {yes, no};
side s = side::buy
answer a = answer::yes
s==a; // gives compilation error
Stronger type
static_assert
03: assert(p!=NULL); //runtime assert
11: static_assert(sizeof(int)==4);
delegating constructor
03: class C { C(){init();} C(int){init();} };
11: class C { C(){} C(int) : C() {} };
in class data member initialization
11: class C { int x=1; };
override in declaration
compilation in all three subclass functions
class P {
virtual void A(int);
virtual void B() const;
void C();
};
class C : public P {
virtual void A(double) override;
virtual void B() override;
virtual void C() override;
};
final class and final virtual function
class C final {}; cannot be derived
class C { void f() final {} }; cannot be override
default constructor
class C { C(int); C()=default; } ;
delete function
class C { C(int); C(double)=delete; C& operator=(const C&)=delete; };
constexpr for compile time
constexpr int MBtoKB(int MB) {return MB*1024;} int kb = MBtoKB(8);
unicode string literal
03: char* s="a";
11:
char* s=u8"a"; // utf8
chat16_t s=u"a";
chat32_t s=U"a";
char* s=R"2\\2"; // 2 backslashes
lambda function and variable capture
[](int x){return x*x;}(2); //4
auto f = [](int x){return x*x;};
f(2); //4
const int y=1;
[&](){return y+1;}; //2
r-value reference
void f(int&) {} void f(int&&) {}
int i=1; f(i); //1st f(1); //2nd
When Standard library return reference?
v[0]; get<0>(t); vector subscript, get tuple
3. Move Semantics
move constructor
copy constructor takes const l-value reference to make expensive deep copy
move constructor takes non-const r-value reference to cheaply steal its members
class C { C(const int&); C(int&&); };
void f(C c) {}
C c; f(c); calls l-value copy constructor
f(C()); calls r-value move constructor
Overload constructor from copy constructor to move constructor
Overload assignment operator from copy assignment operator to move assignment operator
move constructed
string f() {string s; s = "a"; return s; }
string s = f(); // RVO, string move constructed because of returning rvalue, otherwise copy constructed
vector<int> g() {vector<int>v{1}; return v;}
vector<int> v = g(); // RVO, vector move constructor, otherwise copy constructed
4. Perfect Forwarding
template <T> void r(T&& t) {f(std::forward<T>(t);}
T may not be r-value depends on the reference collapse rule that T& &, T&& & and T& && collapses to T& and T&& && collapses to T&&.
T&& is called universal reference that can take r-value, l-value, const and nonconst.
std::forward<T> cast values to T&&
template<T>
void relay(T&& t){foo(std::forward<T>(t));}
relay perfectly forwards lval and rval in one function only not two
std::move<T>(t); t casts to rvalue ref
std::forward<T>(t); t casts to T&& uni ref
5. User defined literals operator""
int, floating, char, string, 1, 2.1, 'a', "ab"
suffix 45, 45u unsigned int, 45l long
constexpr long double operator"" s(long double x) { return 1000*x;}
6. Compiler generated constructor
class C {};
class C { C(); ~C(); C(const C&); C& operator=(const C&); C(C&&); C& operator=(const C&); };
if move exists, copy wont be autogen
if copy exist, move wont be autogen
if destructor exists, only copy but no move, unless C(C&&)=default;
Broken copy constructor
class C {int* p; C(int x): p(new int(x)){} ~C(){delete p;} }; vector<C> v; v.push_back(); v.front().p;
// crash, push_back calls broken copy constructor
Vector requires object to be copyable or removable
7. shared_ptr
internal atomic increment ref count
shared_ptr<C> c = make_shared<C>("m");
9. Why weak_ptr?
shared_ptr leaks when cyclic reference because of mutual ownership
weak_ptr accesses the object without ownership that when and how object is delete is not related to weak_ptr
12. regex
#include <regex>
regex e("exact");
bool b = regex_match(s, e);
regex i("ignore", regex_constant::icase);
Repeat
. any character except newline
? 0 or 1 preceding character, +?-?, exist or not, abc? means ab following by an optional c, {0,1}
*means 0 or more preceding character, or any repeating of previous, abc* means ab followed by any number of c Z0+
+ means 1 or more preceding character, i.e. N, natural number
{3} exactly 3 times
{3,} 3 times or more
{3,5} 3 times to 5 times
Character
[cd] is a character of any one inside
[cd]* means c d cc dd cd ccc ddd cdcd
[^cd] means not c and not d, charet means negate all
Or
"ab|cd" means ab or cd
Escape
\{ means true {
Group the submatch
"(ab)" ab is a group that gives a submatch
"([ab])c*\\1" \1 means submatch 1, slash 1 escape slash 2, so aca bcb matches but acb not. Not submatch is the matched characters that may not be always the same as the group
Predefined set
[[:w:]] a word char : alnum + underscore
Draw a set diagram to match the classes in cplusplus.com
regex_match(s, e); match perfectly, 100%
regex_search(s, e); search partially, similar to google search
"^abc" search begin only (note ^ has overloaded meaning!!!)
"abc$" search end only
13. Regular Expression Grammar
ECMAScript(default), basic, extended, awk, grep, egrep
regex e("^abc.+", regex_constants::grep);
Then "+" is a pure plus not special in grep
smatch for getting matches
smatch is typedef match_results<string>
smatch m;
regex e("([[:w:]]+)@([[:w:]]+)\.c");
bool b=regex_search(s,m,e);
m is vector-like, m.size() is 3
m[0] is whole string, m[1].str() is a, m[2].str() is b, m.prefix().str() is #, m.suffix().str() is !
14. Regex iterator skipped
15 + 16. Chrono skipped
system_clock, steady_clock, high_resolution_clock
std::ratio<1,10> r; r.num; r.den;
17 + 18. Random Number skipped
19. Tuple
pair<int, string> p = make_pair(1,"b");
p.first; p.second;
tuple<int, string, char> t(1,"b",'c');
make_tuple(1,"b",'c');
get<0>(t); get<1>(t); get<2>(t);
get<1>(t) = "new";
get<3>(t); compile error out range
bool b = t2>t1; // lexicalgraphical
t2=t1; member by member copy
tuple of reference
string a="aa"; string b="bb";
tuple<string&, string&> t(a,b);
get<0>(t)="aaa"; // a become aaa
t=make_tuple(ref(a), ref(b));
string x, y;
make_tuple(ref(x), ref(y)) = t;
tie(x, y)=t;
tie(x, std::ignore)=t;
auto t = std::tuple_cat(t1, t2);
tuple_size(decltype(t)):: value; //4
tuple<0, decltype(t)>::type d; // d is a string
Tuple vs struct
struct { string name; int age; } a;
tuple<string, int> b;
a.name; a.age; // more readable
get<0>(b); get<1>(b);
20. When to use tuple?
- One time multiple data transfer
tuple<string, int> getNameAge() {make_tuple("a", 1);}
string x; int y; tie(x, y) = getNameAge();
- compare a group of data
tuple<int, int, int> t1, t2; t1<t2;
- Multi-index map
map<tuple<int, char, float>, string> m;
m[make_tuple(1, 'b', "c")] ="d";
- rotate data
int a, b, c;
tie(b, c, a) = make_tuple(a, b, c);
沒有留言:
張貼留言