【发布时间】:2011-05-10 14:22:20
【问题描述】:
对于一个项目,我必须实现一个 bitset 类。到目前为止,我的代码是:
头文件
#ifndef BITSET_H_
#define BITSET_H_
#include <string>
#include <cmath>
using namespace std;
// Container class to hold and manipulate bitsets
class Bitset {
public:
Bitset();
Bitset(const string);
~Bitset();
// Returns the size of the bitset
int size();
// Sets a bitset equal to the specified value
void operator= (const string);
// Accesses a specific bit from the bitset
bool operator[] (const int) const;
private:
unsigned char *bitset;
int set_size;
// Sets a bitset equal to the specified value
void assign(const string);
};
#endif /* BITSET_H_ */
源文件
#include "bitset.h"
Bitset::Bitset() {
bitset = NULL;
}
Bitset::Bitset(const string value) {
bitset = NULL;
assign(value);
}
Bitset::~Bitset() {
if (bitset != NULL) {
delete[] bitset;
}
}
int Bitset::size() {
return set_size;
}
void Bitset::operator= (const string value) {
assign(value);
}
bool Bitset::operator[] (const int index) const {
int offset;
if (index >= set_size) {
return false;
}
offset = (int) index/sizeof(unsigned char);
return (bitset[offset] >> (index - offset*sizeof(unsigned char))) & 1;
}
void Bitset::assign(const string value) {
int i, offset;
if (bitset != NULL) {
delete[] bitset;
}
bitset = new unsigned char[(int) ceil(value.length()/sizeof(unsigned char))];
for (i = 0; i < value.length(); i++) {
offset = (int) i/sizeof(unsigned char);
if (value[i] == '1') {
bitset[offset] |= (1 << (i - offset*sizeof(unsigned char)));
} else {
bitset[offset] &= ~(1 << (i - offset*sizeof(unsigned char)));
}
}
set_size = value.length();
}
我的问题是我在解构器和分配方法核心转储中的删除语句。不需要释放这个内存吗?从我目前所读到的内容来看,每当你调用 new 时,总是需要使用 delete 命令。
编辑:我已经更改了上面的代码以反映其中一项修复。我在构造函数中添加了 bitset = NULL。这修复了分配方法中的核心转储,但是我仍然在解构器中遇到错误。
【问题讨论】:
-
旁注:
sizeof(unsigned char)始终是1,可能你想要的是std::numeric_limits<unsigned char>::digits或CHAR_BIT。两个整数相除也会产生另一个整数(截断任何分数)。 -
Brian 发现了一个严重错误。上面的某事找到了另一个。还要注意,您分配的字节数是必要的 8 倍: sizeof 以字节为单位,而不是位。 (如果您的系统有
并使用 int8_t,我认为如果您包含它会更容易阅读,否则您自己 typedef 它,那么您可以假设 sizeof == 1)。例如。 bitset = new int8_t[(value.size() + 7) / 8]. -
谢谢你指出这一点。我没有意识到这一点。
-
您接受了一个答案,但评论说它没有解决您的问题,“我的解构器中的删除语句仍然失败”。我的回答(一天后到目前为止为 0 票)可能解决了您的问题。仅供参考......干杯,
-
此类使用资源(动态数组)并尝试管理它。这是不好的。要么管理资源,要么使用资源。对于前者,您有
std::vector,因此您应该只使用std::vector作为您的资源。这大大解决了您的问题。 (显然你也会在实际代码中使用std::bitset。)
标签: c++ memory delete-operator