Source: Aggressive C ++ P11 ~ P23
Level: 200
C ++ has no absolutely appropriate language usage
Note: C ++ is a federated country with four languages: C, object-oriented C ++, template C ++, and STL.
Constdouble aspectratio = 1.653;
Note:For constants, the compiler is used instead of the Preprocessor.Preprocessing will increase the time for tracing variables during debugging and make the program fat. Unless the const compilation process has additional memory overhead, there is no need to define macro constants.
Class gameplayer {static const int numtruns = 5 ;};
Note:Class constant members can often use static to save memory overhead.
Note: If you want to obtain the above address, you cannot write this statement, but you should separate the Declaration and definition:
Class costestimate {static const double fudgefactor ;}; // header file
Const double costestimate: fudgefactor = 1.35; // In the implementation file
The enum hack
Class gameplayer {Enum {numturns = 5 };};
Note: If you do not want others to obtain the address of a constant member, you can use the enum hack method to reject this usage in the compiler.
In addition, like # define, Enum can avoid additional memory allocation when using const because the compiler is too old.
Const rational operator * (const rational & LHS, const rational & RHs );
Note: This is a function with a non-left value constraint, which causes rational A, B, C; (a * B) = C; to be rejected by the compiler.
The compiler satisfies bitwise constness for const member functions
Note: The Compiler meets bitwise constness but does not meet logical constness, so the following situation occurs:
Class ctextblock {
Public:
Char & operator [] (STD: size_t position) const {return ptext [position];} // const member function
PRIVATE:
Char * ptext;
};
Const ctextblock CCTB ("hello ");
Char * Pc = & CCTB [0];
* Pc = 'J'; // now CCTB is "Jello ".
Logical constness
Note: bitwise constness: Do not change any bit in the object, but the above problem may occur.
Logical constness: a const member function can modify some bits of the objects it processes, but cannot be detected during user use.
You can use the mutable keyword to remove bitwise constness:
Class ctextblock {
Public:
STD: size_t length () const;
PRIVATE:
Mutable STD: size_t textlength;
Mutable bool lengthisvalid;
};
STD: size_t ctextblock: length () const
{
If (! Lengthisvalid ){
Textlength = STD: strlen (ptext );
Lengthisvalid = true;
}
Return textlength;
}