我有一个带有一些const
变量的struct
struct HashData
{
const HashKey key;
const void* data;
HashData(const HashKey& key_, const void* data_) : key(key_), data(data_) {}
/* How to write this ?
HashData operator=(const HashData & data)
{
key = std::move(data.key);
return *this;
}
*/
};
还有我使用它的另一个类(class)。
class HashTable
{
std::vector< std::list<HashData> > hashTable; ///< Collisions resolution by chaining.
public:
void insertAtIndex(const std::size_t index, const HashData& data) {
hashTable[index].insert(std::begin(hashTable[index]), data);
}
};
class HashTable
编译不过另一个类
class OpenAddressHashTable
{
std::vector<HashData> hashTable;
public:
void insert(const HashData & data) throw() {
if (data.key == NULLKEY)
throw std::runtime_error("Do not use NullKey");
size_t iteration = 0;
do {
const size_t index = (*hashFunc)(data.key, iteration);
if (hashTable[index].key == NULLKEY) {
// space is free
// ** IMPORTANT **///// Line 131 is next line
hashTable[index] = data;
return ;
}
iteration++;
} while(iteration < hashTable.size());
throw std::runtime_error("No space left");
}
};
我收到这个错误:
g++ -W -Wall -pedantic -std=c++11 hash.cpp
hash.cpp: In member function 'void OpenAddressHashTable::insert(const HashData&)':
hash.cpp:131:24: error: use of deleted function 'HashData& HashData::operator=(const HashData&)'
hash.cpp:26:8: note: 'HashData& HashData::operator=(const HashData&)' is implicitly deleted because the default definition would be ill-formed:
hash.cpp:26:8: error: non-static const member 'const HashKey HashData::key', can't use default assignment operator
我需要将数据放入 vector 中的 std::list
是什么?
我需要在我的 hashTable
中使用指针吗?
最佳答案
你正在做作业:
hashTable[index] = data;
如果您有 const
成员,那将无法正常工作,因为您无法复制或移动到 const
中。编译器错误非常明确:
[the assignment operator] is implicitly deleted because the default definition would be ill-formed
您希望对 key
和 data
进行什么赋值?最简单的事情是删除 const
并在您与用户的界面上强制执行它 - 这样他们就无法从您下面更改 key 。例如:
using InternalHashData = std::pair<HashKey, void*>;
using ExternalHashData = std::pair<const HashKey, void*>;
InternalHashData& something_to_be_returned = ..; // never expose this
return reinterpret_cast<ExternalHashData&>(something_to_be_returned); // this is OK
我能想到的保留 const
的唯一方法是更改您的表:
std::vector<HashData> hashTable;
到
std::vector<std::unique_ptr<HashData>> hashTable;
但是你在每个插入上做额外的分配只是为了保留 const
-ness,这对我来说似乎根本不是一个好的权衡,特别是对于一个唯一目的的容器是性能。
关于c++ - 常量成员和运算符=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721865/