[C++]60个你可能不知道的C++细节

原文转载自水木

发信人: fentoyal (fentoyal), 信区: CPlusPlus
标  题: 60个你可能不知道的C++细节!!
发信站: 水木社区 (Thu Oct  4 06:51:48 2012), 站内
 
标题党了一下,其实是前阵子记得关于C++零碎知识一些读书笔记。这东西经常自己留意不到。有部分其实一般也都用不上(因为用上的都知道了),还有很大一部分是C++11的一些容易忽视(by myself)的细节。
大牛可以帮忙查查错,初学者可以过一遍查缺补漏。写成英文是因为要打算给别人share下,要不自己也懒得整理。

下文中,有些词汇需要解释,见最后边的注解。

原文

Name and Type

  1. The scope of a derived class is treated as nested in its base class when it comes to name lookup. (help understand hiding)
  2. 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 & 
    
  3. In implicit type conversion, char is promoted to int, not short. 

Pointer and Reference

  1. 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 .
  2. 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. 
  3. 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.
  4. 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

  1. A ctor can serve in static_cast .  
  2. 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.
  3. If a class defines a dtor, even if it uses =default, the compiler will not synthesize a move operation for that class.
  4. 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.
  5. 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

  1. 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.
  2. IO stream object can be moved.
  3. 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.
  4. 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?)
  5. 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.
  6. You can use a move_iterator when you want to move all elements from a container to another.

Functions

  1. 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
    …
    
  2. When looking for a best match for overloaded functions, the non-member (normal) functions and member functions race together.
  3. 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
  4. Static member can be used as a default argument before
    definition and even declaration (but, ofc, the declaration should
    exist).

Member functions

  1. 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.
  2. 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.
  3. =default is used when defining a function while =deleted is used when declaring a function.
  4. We can provide a definition for pure virtual function, but we can only write it outside the class.
  5. Virtual function can have default argument, but the one used is
    determined by its static type. No RTTI for this kind of work.
  6. Member functions can also be defined as volatile, only volatile member functions can be called on volatile objects.

Lambda

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. Template member function cannot be virtual.
  2. We can make a template type parameter a friend. 
    template <typename Type> 
    class Bar
    {
        friend Type;
    } 
    

    It is OK when it is instantiated with a built-in type.

  3. Instantiation also happens (if not yet) when assigning the template function to a function pointer / reference.

Access control

  1. 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;} 

    Now, protected_member is public.

  2. 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.
  3. Normal access controls apply to pointers to members.

STL

  1. 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. 

     

  2. 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.
  3. Forward_list does not have size(). (I do not know why exactly)
  4. Forward_list is different, it inserts_after, etc, and uses an off-the-beginning iterator.
  5. String library now have string-to-numeric converting functions.
  6. Reverse_iterator.base() does not yield the adjacent position rather than the same one.
  7. Use make_pair, make_tuple to let compiler deduce types for you.
  8. Iterators for std::set, either cons_iterator or (non-const) iterator are both const_iterators.
  9. Bitset subscription operator [] counts from right to left.
  10. 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? 
    

    Use a pointer or reference to deambiguate:

    int (&funcii )(int , int) = func;
    std::function<int(int, int)> f =  funcii; 
    

  11. The seekg, seekp, tellg, tellp uses the same marker on fstream and stringstream.

Other

  1. Sizeof (*a_null_pointer) is valid. Sizeof (char) is guaranteed to be 1, always.
  2. An enumerator value need not to be unique:
    enum {A = 1, B = 1, C = 1}; //it’s OK 
  3. A definition of a nested class can be outside the enclosing class.
  4. A local class is legal but must be completely defined in the class body.
  5. A constexpr is not required to return a const expression always
  6. 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.
  7. Friendship is not inherited. But, a friend of Base class can access the members of Base part of a Derived object. 
  8. Virtual base classes are always constructed prior to non-virtual base classes regardless of where they appear in the inheritance hierarchy.
  9. noexcept  specifier should not appear in a typedef or type alias(I am not sure why either.)
  10. 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.
  11. A function pointer that not specifying noexcept can point to noexcept functions, but NOT otherwise.

注释

2. decltype

decltype是C++11新引入的关键字,用于返回类型:

  1. 如果e是一个没有外层括弧的标识符表达式或者类成员访问表达式,那么decltype(e)就是e所命名的实体的类型。
  2. 如果e是一个函数调用或者一个重载操作符调用(忽略e的外层括弧),那么decltype(e)就是该函数的返回类型。
  3. 否则,假设e的类型是T:若e是一个左值,则decltype(e)就是T&;若e是一个右值,则decltype(e)就是T。

4. UB

Undefined Behavior - 未定义类型,会导致程序崩溃,或者不可预期的运行结果。编程时需要避免Undefined Behavior。

8. ctor in static_cast

NULL

原文链接: https://www.cnblogs.com/SelaSelah/archive/2012/10/04/2711381.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    [C++]60个你可能不知道的C++细节

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/64737

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午11:30
下一篇 2023年2月9日 上午11:31

相关推荐