mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-06 06:04:39 +01:00
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:
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user