Skip to content

Proposal: Make numel() and shape() safe for empty tensors (null impl_) #22

@Nozom1ff

Description

@Nozom1ff

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(); // ❌ Segfault

This forces users to either:

  1. Use auxiliary boolean flags like has_mask to track tensor validity
  2. Use try-catch blocks around every numel() call
  3. 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();
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions