Is replacing a simple method (e.g vector::size()) by a const reference field a good idea?

Viewed 126

For example, this is my implementation of vector:

template<typename T, /*...*/>
class List {
private:
    /*...*/
    int count;
    int capacity;

public:
    /*constexpr int Count() noexcept {
        return count;
    }*/
    /*constexpr int Capacity() noexcept {
        return capacity;
    }*/

    const int& Count = count;
    const int& Capacity = capacity;

    /*...*/
}

Because these 2 methods just return a private field, ensuring that unable to be changed, and there's no other operations, checks or exceptions in function. Could I take the replace in this situation?

One of the disadvantages I've noticed is that 16 bytes is added for List due to the 2 references(pointers). Could it be optimized?

2 Answers

Could I take the replace in this situation?

You could.

Is replacing a simple method (e.g vector::size()) by a const reference field a good idea?

No. It is a waste of memory.

There is no benefit to adding reference-members to your class -- the public methods that you have commented out are more efficient, since the compiler will not be constrained by aliasing issues when optimizing them. Also there are several drawbacks to using reference-members:

  1. They increase the size of your class-objects (as you mentioned)
  2. A caller might take the address of one of these member variables and hold onto it (e.g. const int * myPtr = &myList.Count), and then try to dereference that pointer after the List object has been destroyed, invoking undefined behavior.
  3. Adding references as member-objects means that the C++ compiler won't generate a default assignment-operator for you; you'll have to define one manually if you want one.

Short, inline-defined methods (like the ones commented out in your posted code) are almost always optimized by the compiler such that there is no function-call overhead involved in calling them; therefore you won't get any performance gain by avoiding them.

Related