【问题标题】:Is it safe to access TArray at an invalid index?在无效索引处访问 TArray 是否安全?
【发布时间】:2017-06-13 17:26:00
【问题描述】:

我想知道以下代码是否会可靠地返回 nullptr 而没有任何复杂性:

TArray<ASomeActor*> SomeActors;

ASomeActor* SomeActor = SomeActors[0];

return SomeActor;

【问题讨论】:

  • 文档的哪一部分令人困惑?
  • 在Unreal Engine API Reference 中它只是说:“数组括号运算符。”。
  • 看起来像std::vector,对std::vector不安全。

标签: c++ arrays unreal-engine4 nullptr


【解决方案1】:

没有。根据documentation,这是不允许的:

传递无效索引(小于 0 或大于或等于 Num())将导致运行时错误。

【讨论】:

    【解决方案2】:

    尝试访问 TArray 的无效索引并不安全,但引擎提供了一种在尝试读取索引之前检查索引的便捷方法:

    TArray<ASomeActor*> SomeActors;
    if (SomeActors.IsValidIndex(0))
    {
        ASomeActor* SomeActor = SomeActors[0];
        return SomeActor;
    }
    else
    {
        return nullptr;
    }
    

    会更安全。在尝试读取数组之前检查数组的大小也是完全合理的:

    If (SomeActors.Num() > 0)
    {
        return SomeActors[0];
    }
    

    如果需要进行 const 赋值,可以使用三元运算符:

    const ASomeActor* SomeActor = SomeActors.IsValidIndex(0) ? SomeActors[0] : nullptr;
    

    【讨论】:

      【解决方案3】:
      TArray<ASomeActor*> SomeActors;
      ASomeActor* SomeActor = SomeActors[0];
      return SomeActor;
      

      以上代码导致运行时错误,因为索引大于或等于数组的大小。

      在使用索引访问元素之前,请检查索引与数组的大小。索引应该小于数组的大小。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-11
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2010-10-30
        相关资源
        最近更新 更多