Practical use of mutable

January 3rd, 2008

I have finally found a practical use of mutable keyword in C++ :D

Suppose we have a class and we want to do some "lazy loading":

C++:
class Foo
{
    private:
        Bar *bar;
    public:
        const Bar& GetBar() const;
};

const Bar& Foo::GetBar() const
{
    // lazy loading
    if(bar == NULL)
    {
        bar = new Bar();
    }
}

Everything would be fine but the const keyword does not allow us to change a value of a bar pointer.
That's the place where mutable is useful :)

C++:
class Foo
{
    private:
        mutable Bar *bar;
    public:
        const Bar& GetBar() const;
};

const Bar& Foo::GetBar() const
{
    // lazy loading
    if(bar == NULL)
    {
        bar = new Bar();
    }
}

Happy coding :)

Vomit C++

November 17th, 2007

Few days ago I found very interesting piece of code in polish usenet. The code is correct and it works fine but it looks like... yes, like vomit. C++ programmers, can I have a request? Please, do not move features from other languages that we can live without, to the C++.

C++:
void increment(int &i)
{
    ++i;
}

static void test1()
{
    boost::function<void (int &)> add1=::increment;
    std::vector<std::vector<int>> vec(10, std::vector<int>(10, 2010));
    std::for_each(vec.begin(), vec.end(), boost::lambda::bind(boost::lambda::ll::for_each(),
                boost::lambda::bind(boost::mem_fn((std::vector<int>::iterator(std::vector<int>::*)())
                        &std::vector<int>::begin), boost::lambda::_1),
                boost::lambda::bind(boost::mem_fn((std::vector<int>::iterator(std::vector<int>::*)())
                        &std::vector<int>::end), boost::lambda::_1),
                add1));
    std::for_each(vec.begin(), vec.end(), boost::lambda::bind(boost::lambda::ll::copy(),
                boost::lambda::bind(boost::mem_fn((std::vector<int>::iterator(std::vector<int>::*)())
                        &std::vector<int>::begin), boost::lambda::_1),
                boost::lambda::bind(boost::mem_fn((std::vector<int>::iterator(std::vector<int>::*)())
                        &std::vector<int>::end), boost::lambda::_1),
                std::ostream_iterator<int>(std::cout, " ")));
    std::cin.get();
}

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!