Why is it useful to create a const function?

Why is it so useful to create a const function if you can only read variables, but not write (class variable)?

+3
source share
6 answers

If you pass something else, the const or const pointer refers to an instance of your class, then it can only call the methods of the const class (if any).

Obviously, if you never worry about const-correctness with your types, you can ignore this.

I believe this can also help the compiler optimize things in certain situations, although I doubt it even if it helps, allowing this small improvement (if any) to dictate how you wrote the code, there will be a case of premature optimization in most situations.

+3
source

So that you do not “accidentally” change one of the class variables. This is just a safety measure.

(If you use the const keyword after a function that modifies any member of the class data - either directly or through another function call - you will get a compilation error).

+3
source

, const . , , .

const-correctness, , ( ), slim.

:

#include <vector>
#include <algorithm>

struct X
{
    int n;
    bool operator< (X b)
    { 
        return n < b.n;
    }
};

int main()
{
    std::vector<X> vec;
    std::sort(vec.begin(), vec.end());
}

codepad.org

In function 'const _Tp& std::__median(const _Tp&, const _Tp&, const _Tp&) [with _Tp = X]':
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:2642:   instantiated from 'void std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator, _Size) [with _RandomAccessIterator = __gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<X*, __gnu_norm::vector<X, std::allocator<X> > >, __gnu_debug_def::vector<X, std::allocator<X> > >, _Size = int]'
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:2713:   instantiated from 'void std::sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = __gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<X*, __gnu_norm::vector<X, std::allocator<X> > >, __gnu_debug_def::vector<X, std::allocator<X> > >]'
t.cpp:17:   instantiated from here
Line 90: error: no match for 'operator<' in '__a < __b'

, stdlib, , . , .

: const, . . - .

+1

const, const member.

0

, ( ). const-ness this , . (, " " )

0

, , . , , , , , , . , .

0
source

Source: https://habr.com/ru/post/1781944/


All Articles