samedi 12 août 2017

Smart pointer operator[] "no match" when type is array with known length

Given the below code:

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);
}

I get the following error:

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];

I thought that the typedef would give me a smart pointer containing a pointer to an array of uint8_t and so operator[] should be indexing into that array. My best guesses at what's happening is that I'm instead saying that I want a unique_ptr to a pointer to an array of uint8_t. I think I see a couple of ways out of this but I'm not sure which is best

  1. typedef std::unique_ptr<uint8_t[]> sha256hash; compiles, but I'm not entirely sure that my overloaded operator won't try to print any unique_ptr to an array of ints.
  2. I make a container struct for the int array, and put a unique_ptr around that.

Aucun commentaire:

Enregistrer un commentaire