c++pass-by-referenceimmutabilitypass-by-valuepass-by-const-reference

C++ Immutable custom class pass by reference or value


I've made a custom class which involves a ton of number and string computation. I've made my class immutable by only providing accessors and no mutators. Once the object is constructed, there is no changing a single property of it.

My question from here is, currently all of my functions are pass by value. If you have an immutable object, is pass by reference even needed anymore? Is pass by value wasteful in terms of memory since copies need to constantly be created?

For example:

class MyInteger
{
    private:
        const int val;

    public:
        MyInteger(const int a) : val(a) { };    
        int getValue() const { return val; }
        MyInteger add(const MyInteger other)
        {
            return MyInteger(val + other.getValue());   
        }
}

Solution

  • Pass-by-value requires copying. If your class is large and copying costs, you could make it pass-by-reference to avoid such copy.

    Since it's immutable you can pass it by reference-to-const.

    class MyInteger
    {
        private:
            const int val;
    
        public:
            MyInteger(const int a) : val(a) { };    
            int getValue() const { return val; }
    
            MyInteger add(const MyInteger& other) const // Note this is passed by reference to const now
            //                           ~
            {
                return MyInteger(val + other.getValue());   
            }
    }