zoukankan      html  css  js  c++  java
  • effective C++ 3 use const whenever possible

    const一直是个我记不太清楚的东西,这一节内容还挺多,希望自己可以记住。

    首先是const指针的问题,到底指针是const,还是指针指向的东西是const。这里提供了一条很简单的法则,那就是看const出现在星号*的左边还是右边:const在*左边,那就是指向的东西是const,如果在*右边,那就是指针本身是个const。

    比如 

    char test[] = "test";
    const char *p = test; //non-const pointer, const data
    char* const p = test; //const pointer, non-const data

    STL的迭代器和指针差不多,所以也有上面的规则。

    下面是const在关于函数声明时的应用。

    首先可以让函数的返回值是一个const,借用原文中的例子:

    class Rational { ... };
    const Rational operator* (const Rational& lhs, const Rational& rhs;

    因为操作符返回的是const,所以就很容易避免类似下面这种错误:

    if(a*b==c)时不小心笔误漏掉了一个=,写成了if(a*b=c)。

    下面再看一下const成员函数:

    因为const成员函数是不修改对象的成员变量的,所以把一个成员函数定为const是为了确认其可以作用于const对象。

    如果需要在const成员函数里修改成员变量,可以在可能被修改的成员变量前加上mutable,这样const成员函数就可以修改这个变量了。

    如果两个成员函数仅仅是const不同(一个是const,一个不是),那么是可以被重载的。假如说这两个成员函数完成的事情是一样的,仅仅是const的区别,为了避免重复,可以在non-const函数里调用const函数,如下:

    class TextBlock {
        const char & operator[] (std::size_t position) const
        {
    
            return text[position];
        }
    
        char operator[] (std::size_t position)
        {
            return
                const_cast<char&>( //去掉const
                    static_cast<const TextBlock&>(*this) //为*this加上const
                        [position] //调用const op[]
                );
        }
    ...
    }

    去除const只能由const_cast来完成,这个以及其他cast的用法似乎后面也会讲到。

    需要注意的是不能在const里面调用non-const函数。

  • 相关阅读:
    MySQL "show users"
    MySQL
    A MySQL 'create table' syntax example
    MySQL backup
    MySQL show status
    Tomcat, pathinfo, and servlets
    Servlet forward example
    Servlet redirect example
    Java servlet example
    How to forward from one JSP to another JSP
  • 原文地址:https://www.cnblogs.com/parapax/p/3637657.html
Copyright © 2011-2022 走看看