Work with constant and non-constant functions - C ++

I have 3 classes. It has the simplest form, it seems

class tree
{
public:
    tree_node* find_node(const std::string& text) {
       return factory.find(text);
    }
private:
    tree_node_factory factory;
}

class tree_node
{
public:
    tree_node(const std::string& text) : text_(text) {}

    const std::string& text() const {
       return text_;
    }

    void set_parent(const tree_node* new_parent);

private:
    std::string text_;
}

class tree_node_factory
{
public:
    tree_node* find(const std::string& text);
private:
    std::vector<tree_node*> allocated_nodes;
}

I do not want to allow users treeto modify tree_nodereturned methods such as find_node. So I changed, find_nodeand tree_node_factory::findto,

const tree_node* find_node(const std::string& text) const {
    return factory.find(text);
}

const tree_node* find(const std::string& text) const;

The problem treeinternally must be able to modify nodes and work with methods such as set_parent. But since the factory returns only tags const, I ended up adding another overload (not a const version) to the factory find.

tree_node* find(const std::string& text);

I wonder is this the right way to deal with such problems? I see that the code is duplicated in const and non-const versions.

Any thoughts ..?

+3
source share
2

3 ++ . , const this, const, const. ; const- undefined, this const const .

:

const std::string& operator[](size_t index) const
{
    // some other code

    // since `this` isn't really const, this is modifiable 
    return mData[index]; 
}

std::string& operator[](size_t index)
{
    return const_cast<std::string&> // (3) take const off result
            (static_cast<const my_type&> // (1) add const
            (*this)[index]); // (2) use const version

}

. .

: const "" const, undefined. , this. :

const std::string& operator[](size_t index) const
{
    static const std::string constString = "Don't modify me.";

    if (index == 0)
    {
        // even though `this` isn't really const, this is NOT modifiable
        return constString; 
    }

    return mData[index - 1];
}

std::string& operator[](size_t index)
{
    return const_cast<std::string&> // (3) !!! take const off result !!!
            (static_cast<const my_type&> // (1)
            (*this)[index]); // (2)

}

, . , .

+7

, ++ ( ) , , . const_cast.

+3

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


All Articles