Examples of const function parameters in C++

Examples with int

Compiles without warnings with MSVC:

class A
{
public:

    void f(const int a);
};

void A::f(int a)
{
    a = 10;
    std::cout << a;
}

error C3892: ‘a’: you cannot assign to a variable that is const:

class A
{
public:

    void f(int a);
};

void A::f(const int a)
{
    a = 10;
    std::cout << a;
}

std::move and std::forward

We can’t make the parameters const if we move or forward them. For example, func parameter can’t be const in the code below:

template <size_t read_length, class Func>
        requires std::invocable<Func, const boost::system::error_code&, std::size_t>
void asyncRead(uint8_t (&data)[read_length], Func&& func)
{
    stream().async_read_some(
            boost::asio::buffer(data, read_length),
            std::forward<Func>(func));
}

Examples with a structure

This compiles without warnings with MSVC:

struct Value
{
    int x;

    std::string y;
};

class A
{
public:

    void f(Value val);
};

void A::f(const Value val)
{
    std::cout << val.x;
}

and there are no warnings either:

struct Value
{
    int x;

    std::string y;
};

class A
{
public:

    void f(const Value val);
};

void A::f(Value val)
{
    val.y = "abc";
    std::cout << val.x << " " << val.y;
}

Automatic variables

We probably also make automatic variables const if we do not modify them.

Leave a Reply

Your email address will not be published. Required fields are marked *