【发布时间】: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。我想我看到了几种解决方法,但我不确定哪种方法最好
-
typedef std::unique_ptr<uint8_t[]> sha256hash;编译,但我不完全确定我的重载运算符不会尝试将 any unique_ptr 打印到整数数组。 - 我为 int 数组创建了一个容器结构,并在其周围放置了一个 unique_ptr。
【问题讨论】:
-
似乎
operator[]是专门为std::unique_ptr<T[]>定义的,不适用于std::unique_ptr<T[N]>,所以typedef std::unique_ptr<uint8_t[]> sha256hash;似乎可以工作 -
如果您担心意外重载,您可以非常具体地使用自定义删除器,例如
typedef std::unique_ptr<uint8_t[], MyDeleter> sha256hash; -
感谢您的回复。我最终选择了选项 2。我稍后会发布我的更改。
标签: c++11 smart-pointers