-
Notifications
You must be signed in to change notification settings - Fork 32
Proposal: Make numel() and shape() safe for empty tensors (null impl_) #22
Copy link
Copy link
Open
Description
Description
Currently, when a Tensor is default-constructed, its impl_ is nullptr. Calling any method like numel() or shape() on such an
empty tensor causes a segmentation fault:
Tensor t; // impl_ = nullptr
t.numel(); // ❌ Segfault - accesses nullptr->shape()
t.shape(); // ❌ SegfaultThis forces users to either:
- Use auxiliary boolean flags like has_mask to track tensor validity
- Use try-catch blocks around every numel() call
- Manually create valid empty tensors like Tensor(std::vector{}, {0})
| Considering that we sometimes need to create an optional tensor, which may be assigned later, it is cumbersome to perform its safety check each time.
Proposed Solution
Make numel() and shape() safe for empty tensors by checking impl_ first:
size_t numel() const {
if (!impl_) return 0; // Safe for empty tensors
return impl_->shape().elements();
}
Shape shape() const {
if (!impl_) return Shape{}; // Return empty shape
return impl_->shape();
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels