0

I would like to know if the difference of "2 concrete nullptr" of the same type is guaranteed to be equal to 0. I can't find anything in the C++ standard that guarantees that.

template <typename T>
std::ptrdiff_t diff() {
    T* p = nullptr;
    T* q = nullptr;
    return p - q;
}

In other words, does this code "has" to return 0?

The reason I am asking this question is that I want to implement my own vector class with

template <typename T>
class Vector {
private:
    T* data_;
    T* size_;
public:
    int size() const {
        return static_cast<int>(size_ - data_);
    }
}

and I am wondering if it is allowed to put data_ = size_ = nullptr when I construct a vector of length 0.

InsideLoop
  • 6,063
  • 2
  • 28
  • 55

1 Answers1

0

Just quote @hdv. No, it is not. nullptr is a literal of a special type std::nullptr_t, which is not an integer type. In fact, nullptr - nullptr is an error because no - operator is defined for that type. You need to convert nullptr to a concrete pointer type (like the question does) to make the subtraction work.

Bart Bartoman
  • 756
  • 4
  • 14