samedi 18 juillet 2020

Returning by const value and assigning to a non const variable compiles

I don't understand why the following code is allowed to use the non const version of foo. I would like to forbid a const Array variable to provide a non const ArrayView.

#include <iostream>

struct ArrayView
{
    ArrayView() = default;
    ArrayView(const ArrayView&) = delete;
    ArrayView(ArrayView&&) = delete;

    void foo() {std::cout << "non const" << std::endl;}
    void foo() const {std::cout << "const" << std::endl;}
};

struct Array
{
    const ArrayView createView() const
    {
        return {};
    }
};

int main()
{
    const Array arr{};
    auto view = arr.createView();
    view.foo();

    return 0;
}

output:

non const

I have gcc 10.1.0 on windows 10.

Aucun commentaire:

Enregistrer un commentaire