[C++]60个你可能不知道的C++细节
原文转载自水木
发信人: fentoyal (fentoyal), 信区: CPlusPlus
标 题: 60个你可能不知道的C++细节!!
发信站: 水木社区 (Thu Oct 4 06:51:48 2012), 站内
标题党了一下,其实是前阵子记得关于C++零碎知识一些读书笔记。这东西经常自己留意不到。有部分其实一般也都用不上(因为用上的都知道了),还有很大一部分是C++11的一些容易忽视(by myself)的细节。
大牛可以帮忙查查错,初学者可以过一遍查缺补漏。写成英文是因为要打算给别人share下,要不自己也懒得整理。
下文中,有些词汇需要解释,见最后边的注解。
原文
Name and Type
- The scope of a derived class is treated as nested in its base class when it comes to name lookup. (help understand hiding)
- Decltype 注 yields the corresponding type for a VARIABLE and a reference for assignable EXPRESSION, and a value for non-assignable EXPRESSION. e.g.
decltype(ref_int) //int & decltype(ref_int + 0) //int decltype(val_int) // int decltype((val_int)) // int &
- In implicit type conversion, char is promoted to int, not short.
Pointer and Reference
- A past-the-end pointer is not an invalid pointer. Though it also should not be dereferenced, it can be used to compare with the other pointers pointing to the same array. In contrast, comparing two pointers pointing to two unrelated object is UB 注.
- A reference is always treated as the object it refers, such as, sizeof(ref), typeid(ref), etc, all info is about the underlying object, with only one exception: decltype(ref) gives the reference type.
- A pointer got from new Type[0] is not a nullptr but a pass-the-end pointer, it serves just like vec.end() when the vector is empty.
- Use std::less<T>()(a, b) instead of ‘<’ when writing a template. Because if T are pointers and they are not pointing to the same array, using ‘<’ on them is UB.
Ctor/Dtor
- A ctor can serve in static_cast 注.
- Inherited ctors inherits explicit/constexpr properties. It does not inherit default arguments. Instead it gets multiple ctors in which each parameter with a default argument is successively omitted.
- If a class defines a dtor, even if it uses =default, the compiler will not synthesize a move operation for that class.
- The reason why the member initialization order depends on the definition order rather than the order in which they appear in the initialize list is, dtor must reverse the order and there is no way for a dtor to know the order in which you initialized the members.
- When you use ‘=default’ to force a compiler to generate a default move ctor for your class, but the compiler cannot (e.g. not all members are movable), the compiler will turn it into ‘=deleted’.
Move
- Compiler uses the copy ctor for move if you do not provide one. But, if you refuse to provide any copy-control members (assignment operator, copy ctor, etc) and all non-static data members are movable, you will get a real synthesized move ctor from compiler.
- IO stream object can be moved.
- After move operation, do not assume any state of the moved obj. e.g. People may assume a moved vector has size() as 0 and the call of empty() on it return true. But it is not necessarily the case: perhaps the underlying whole pimpl object was moved away, the call of empty() or size() are forwarded to a null pointer.
- The std::containers only move its elements when the elements have a nonexcept move ctor. Otherwise it cannot guarantee exception safety when moving the container. (Is this part of the reason that VC11 does not support nonexcept keyword yet?)
- Classes that define a move ctor/assignment operator must also define their own copy operations; otherwise, those copy operations are defined as $deleted$ by default.
- You can use a move_iterator when you want to move all elements from a container to another.
Functions
- Using directives create an overlord set of functions from different namespaces:
using namespace sp1; //has print(int) using namespace sp2;//has print(double) … print(1); //sp1::print print(1.2);//sp2::print …
- When looking for a best match for overloaded functions, the non-member (normal) functions and member functions race together.
- Each function default parameter can have its default specified only once.Any subsequent declaration can add a default only for a parameter that has not previously had a default specified.
int f(int , int = 2); int f (int =1, int);// OK, incremental specification - Static member can be used as a default argument before definition and even declaration (but, ofc, the declaration should exist).
Member functions
- When using = default, (as with other member fuctions), if it appears in class, the default ctor will be inlined; if it appears outside the class, it is not by default.
- Besides const, you can place a reference qualifier
on a member function to indicate this pointer is pointing to a rvalue or
lvalue. E.g.
void mem_func(int ) const &&
means, mem_func(const && this_obj, int); The && here has nothing to do with move semantic. It avoids some silly statement like : str0 + str1 = “abc”. Operator=() should certainly behave differently when *this is a rvalue or a lvalue.
Btw, it is nice but not supported by many compilers yet. - =default is used when defining a function while =deleted is used when declaring a function.
- We can provide a definition for pure virtual function, but we can only write it outside the class.
- Virtual function can have default argument, but the one used is determined by its static type. No RTTI for this kind of work.
- Member functions can also be defined as volatile, only volatile member functions can be called on volatile objects.
Lambda
- Lambdas are function objects with deleted default ctor, deleted assignment operators and default dtor and it has a member ‘operator()’ which is a const member by default. Whether it has a defaulted or deleted copy/move ct depends on the captured data members.
- The value (as opposed to reference) captured by a lambda is const, you cannot change its value. This is because by default lambda is a const object and the captured values are its data members. You can override its constness by adding a mutable keyword following lambda.
- In a lambda function, when the return type is not specified, the function body is just a return statement, the return type is inferred from it, or it is void.
- We can omit parameter list and return type of lambda. So a simplest form and fully spelled formed should be:
auto f = []{}; auto f = [captures](parameters) mutable -> returntype {}
Template
- Template member function cannot be virtual.
- We can make a template type parameter a friend.
template <typename Type> class Bar { friend Type; }
- Instantiation also happens (if not yet) when assigning the template function to a function pointer / reference.
Access control
- Other than narrowing down the access control during inheritance (by public, protected, private derivation), we have a way to enlarge it:
class Derived: private Base{ public: using Base::protected_member; }
- The protected/public member can be accessed from derived class, even if it uses private derivation. The access control of private derivation has effect on how to use the derived class, not the base class.
- Normal access controls apply to pointers to members.
STL
- The STL containers now have a cbegin() and cend, which are specifically designed for auto:
auto citer = vec.cbegin()//always const_iter regardless the container type.
- Std::swap() only invalidates the iterators on std::string. It does not invalidate iterators on other types of containers. They are pointing to the same elements in the swapped container.
- Forward_list does not have size(). (I do not know why exactly)
- Forward_list is different, it inserts_after, etc, and uses an off-the-beginning iterator.
- String library now have string-to-numeric converting functions.
- Reverse_iterator.base() does not yield the adjacent position rather than the same one.
- Use make_pair, make_tuple to let compiler deduce types for you.
- Iterators for std::set, either cons_iterator or (non-const) iterator are both const_iterators.
- Bitset subscription operator [] counts from right to left.
- We can use std::function to store a function directly but cannot when it has overloaded versions:
int func(int, int); int func(double, double); std::function<int(int, int)> f = func; //which?
int (&funcii )(int , int) = func; std::function<int(int, int)> f = funcii;
- The seekg, seekp, tellg, tellp uses the same marker on fstream and stringstream.
Other
- Sizeof (*a_null_pointer) is valid. Sizeof (char) is guaranteed to be 1, always.
- An enumerator value need not to be unique:
enum {A = 1, B = 1, C = 1}; //it’s OK
- A definition of a nested class can be outside the enclosing class.
- A local class is legal but must be completely defined in the class body.
- A constexpr is not required to return a const expression always
- A constexpr is not required to be defined when the literal value is used. But it still needs a definition when the run time properties (like address operator &) are required.
- Friendship is not inherited. But, a friend of Base class can access the members of Base part of a Derived object.
- Virtual base classes are always constructed prior to non-virtual base classes regardless of where they appear in the inheritance hierarchy.
- noexcept specifier should not appear in a typedef or type alias(I am not sure why either.)
- The compiler will generate (when needed) the nonexcept ctor / copy-control members / dtor if the corresponding operations for all of its members promise not to throw.
- A function pointer that not specifying noexcept can point to noexcept functions, but NOT otherwise.
注释
2. decltype
decltype是C++11新引入的关键字,用于返回类型:
- 如果e是一个没有外层括弧的标识符表达式或者类成员访问表达式,那么decltype(e)就是e所命名的实体的类型。
- 如果e是一个函数调用或者一个重载操作符调用(忽略e的外层括弧),那么decltype(e)就是该函数的返回类型。
- 否则,假设e的类型是T:若e是一个左值,则decltype(e)就是T&;若e是一个右值,则decltype(e)就是T。
4. UB
Undefined Behavior - 未定义类型,会导致程序崩溃,或者不可预期的运行结果。编程时需要避免Undefined Behavior。
8. ctor in static_cast
NULL