02 C++: C++ Advance Notes (TBC)
1. Const
const int i=0;
const int * const p = &i; // read from right
const_cast<int&>(i)=1; // ok, 1
int j=0;
const_cast<const int&>(j)=1; // error assign read only location
Why const?
Self documented intention. Avoid inadvertent write. Compiler optimize variable when it is defined with const by storing to program executable at compiler time.
2. Const in function
class C { void f(int); void f(const int); };
cannot compiler overload f by const param
class C { const string & getName(); }; is good to return by const string ref.
const member function overloading
class C { void f() {}void f() const {} };
const reference argument overloading
class C { void f(string); void f(const string&); };
3. logic const with mutable vs bitwise const by compiler
class C { volatile int counter; } ;
const_cast<C*>(this)->count++; // also ok
4. Compiler generated functions
copy constructor, copy assignment operator, default constructor, destructor
All public, inline, generated only if have caller
class C{};
class C {
C(const C&){} // member initialization
C& operator=(const C&){} // member copy, not generated if const member or reference member
C(); // base default, member default
~C(); // Member destroy, base destroy
class C { C()=default; }; // force generate
5. Disallow function
class C { public: C(C&)=delete; }; // no call
Use =delete or privatize the function
private destructor does not compile when used as stack object, forcing store at heap
6. Virtual destructor
factory pattern is a centralized place to produce objects.
Use virtual destructor.
Use shared_ptr without virtual destructor also works, but unique_ptr will not work.
All C++ standard library has no virtual destructor.
7. Exception in destructor
Crash if exception thrown in destructor
Solution is to swallow all exceptions in destructor, or move exception-safe code away from desctructor
What is rvalue?
R value cannot be addressed
2 = i; so 2 is r value
&(i+1); so (i+1) is r value
(i+1)=2; so (i+1) is r value
&C(); so C() is r value
&sum(1,2); so sum(1,2) is r value
What is reference?
A variable reference a lvalue
So int& i=5; compiles error
const int& i=5; is 2 step. Step 1: temp l value assigned with 5 2. Reference a temp l-value
int f(int& i) {}; f(1); //compile error
int i=1; int j=i; l-value i is implicitly transformed to r-value before assignment
r-value can be used to create l-value:
int v[3]; *(v+2)=0; // r-val become l-val
Misconcept: Operator can return l-value
int g; int& f(){return g;};
f()=1;
(a+b)=1;
v[0]=1;
Misconcept: l-value always modifiable
In C yes. In C++ no, because of const int i;
Misconcept: r-value not modifiable
No. c().f(); the r value c() state is modified.
Expression is either l-value or r-value where l-value has identifiable memory address.
沒有留言:
張貼留言