Switch Ptr to a C++ pointer using the nonnull attribute (#831)

The advantage is a C++ pointer is special, and this approach eliminates the Ptr class type that was causing problems in conversions. Attribute suggestion was courtesy of chandlerc. We're sticking with the Ptr name because it's shorter than Nonnull, and we're likely to keep this in lots of places.
This commit is contained in:
Jon Meow
2021-09-16 13:05:25 -07:00
committed by GitHub
parent 395a331cde
commit ff319d311a
6 changed files with 28 additions and 62 deletions
+1 -34
View File
@@ -5,44 +5,11 @@
#ifndef EXECUTABLE_SEMANTICS_COMMON_PTR_H_
#define EXECUTABLE_SEMANTICS_COMMON_PTR_H_
#include <memory>
#include <vector>
#include "common/check.h"
namespace Carbon {
// A non-nullable pointer. Written as `Ptr<T>` instead of `T*`.
template <typename T>
class Ptr {
public:
explicit Ptr(T* ptr) : ptr(ptr) { CHECK(ptr != nullptr); }
template <typename OtherT,
std::enable_if_t<std::is_convertible_v<OtherT*, T*>>* = nullptr>
Ptr(Ptr<OtherT> other) : ptr(other.Get()) {}
Ptr(std::nullptr_t) = delete;
Ptr(const Ptr& other) = default;
Ptr& operator=(const Ptr& rhs) = default;
auto operator*() const -> T& { return *ptr; }
auto operator->() const -> T* { return ptr; }
T* Get() const { return ptr; }
friend auto operator==(Ptr lhs, Ptr rhs) { return lhs.ptr == rhs.ptr; }
friend auto operator!=(Ptr lhs, Ptr rhs) { return lhs.ptr != rhs.ptr; }
private:
T* ptr;
};
template <typename T>
auto PtrTo(T& obj) -> Ptr<T> {
return Ptr<T>(&obj);
}
using Ptr = T* _Nonnull __attribute__((nonnull));
} // namespace Carbon