【问题标题】:Smart pointer operator[] "no match" when type is array with known length当类型是已知长度的数组时,智能指针运算符 []“不匹配”
【发布时间】:2017-08-13 05:01:10
【问题描述】:

给定以下代码:

typedef std::unique_ptr<uint8_t[SHA256::DIGEST_SIZE]> sha256hash;

std::ostream& operator<<(std::ostream& os, const sha256hash &hash) {
    // Save old formatting
    std::ios oldFormat(nullptr);
    oldFormat.copyfmt(os);

    // Set up formatting
    os << std::setfill('0') << std::setw(2) << std::hex;

    // Do our printing
    for (int i = 0;i < SHA256::DIGEST_SIZE; i++)
      os << hash[i];

    // Restore formatting
    os.copyfmt(oldFormat);
}

我收到以下错误:

In function ‘std::ostream& operator<<(std::ostream&, const sha256hash&)’:
error: no match for ‘operator[]’ (operand types are ‘const sha256hash {aka const std::unique_ptr<unsigned char [32]>}’ and ‘int’)
   os << hash[i];

我认为 typedef 会给我一个智能指针,其中包含一个指向 uint8_t 数组的指针,因此 operator[] 应该索引到该数组。我对正在发生的事情的最佳猜测是,我是说我想要一个指向 uint8_t 数组的指针的 unique_ptr。我想我看到了几种解决方法,但我不确定哪种方法最好

  1. typedef std::unique_ptr&lt;uint8_t[]&gt; sha256hash; 编译,但我不完全确定我的重载运算符不会尝试将 any unique_ptr 打印到整数数组。
  2. 我为 int 数组创建了一个容器结构,并在其周围放置了一个 unique_ptr。

【问题讨论】:

  • 似乎operator[] 是专门为std::unique_ptr&lt;T[]&gt; 定义的,不适用于std::unique_ptr&lt;T[N]&gt;,所以typedef std::unique_ptr&lt;uint8_t[]&gt; sha256hash; 似乎可以工作
  • 如果您担心意外重载,您可以非常具体地使用自定义删除器,例如 typedef std::unique_ptr&lt;uint8_t[], MyDeleter&gt; sha256hash;
  • 感谢您的回复。我最终选择了选项 2。我稍后会发布我的更改。

标签: c++11 smart-pointers


【解决方案1】:

由于@PeterT 的input,我最终选择了第二个选项。自定义删除器似乎离我太远了,这很容易集成到我已经存在的代码中。这是我的更改:

//! Light wrapper around SHA256 digest
class SHA256Hash {
  //! The actual digest bits.
  uint8_t buff[SHA256::DIGEST_SIZE];
public:
  //! Pointer to a hash.
  typedef std::unique_ptr<SHA256Hash> ptr;

  //! Default constructor
  SHA256Hash() : buff() { }

  //! Operator to offer convenient buffer access
  uint8_t &operator[](const uint8_t i) { return buff[i]; }

  //! Operator to offer convenient buffer access
  const uint8_t &operator[](const uint8_t i) const { return buff[i]; }

  //! Offers access to the underlying digest
  uint8_t *get() { return (uint8_t *) &buff; }
};

// Delegate to the version that prints references
std::ostream &operator<<(std::ostream &os, const SHA256Hash::ptr &hashp) {
  os << *hashp;
  return os;
}

std::ostream &operator<<(std::ostream &os, const SHA256Hash &hash) {
    // Save old formatting
    std::ios oldFormat(nullptr);
    oldFormat.copyfmt(os);

    // Set up formatting
    os << std::setfill('0') << std::setw(2) << std::hex;

    // Do our printing
    for (int i = 0;i < SHA256::DIGEST_SIZE; i++)
      os << (int) hash[i];

    // Restore formatting
    os.copyfmt(oldFormat);

    return os;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2021-10-24
    • 1970-01-01
    • 2023-03-21
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多