0

Let's say I have a class as

template <class T>
class c_array {
private:
    T* m_arr;
    int m_length = 0;

public:
    T pop() {
        if (m_length==0) {
            //???
        }

        m_length--;
        return m_arr[m_length];
    }
};

What should I return if length==0?

Returning NULL gives a warning:

"warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]"

Trying

std::vector<int> vect;

int b = vect.pop_back();

Gives the error "error: void value not ignored as it ought to be"

Dkui2200
  • 27
  • 3
  • 1
    usually user expected to check if container is empty. – Kao Feb 07 '21 at 14:37
  • 1
    You need to return a valid `T`. You'll note that the `std::vector::pop_back` doesn't return the poppped element for (presumably) this reason. Nowadays, using [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional) can be idiomatic. – Brian61354270 Feb 07 '21 at 14:38
  • 2
    You can throw an exception for such cases. – πάντα ῥεῖ Feb 07 '21 at 14:38

1 Answers1

4

What should I return if length==0?

There are a few typical ways to handle this.

  • Don't perform any check and do the same regardless of size and specify that non emptiness is a pre condition. If the caller violates the pre condition, then behaviour is undefined. This is the most efficient alternative, but also least safe.
  • Abort the program. This isn't very convenient.
  • Instead of returning a value, throw an exception when the element doesn't exist.
  • This doesn't apply to pop in particular, but to similar functions that keep the element in container: Instead of returning an object in general, return an iterator. In case element doesn't exist, return an iterator that represents non-existing element. Typically, iterator to element past the end is used.
eerorika
  • 232,697
  • 12
  • 197
  • 326