我认为您的代码比它可能需要的更复杂。我会考虑使用std 容器,例如std::vector 或任何更适合您需求的容器。通常,除非确实有必要,否则应避免使用多级间接,在这种情况下似乎没有必要。
理解指针
您首先声明了BankTeller **tellers,它是一个指向BankTeller 的指针。导致代码中段错误的行是*tellers = new BankTeller[count];。此行返回一个指向 BankTeller 对象数组的指针,但您使用双精度 ** 的声明表示它应该获取一个指向 pointers 到 BankTeller 对象的数组。分配的值仍被解释为地址(它不是)并最终尝试访问无效的内存位置,这会触发段错误。
应该是*tellers = new BankTeller*[count];。注意左括号前的*。这行代码为您提供了一个 pointers 数组,指向BankTeller 对象。
简单示例
为了说明,忘记BankTellers,让我们回到原语。
#include <iostream>
using namespace std;
int main()
{
const size_t max = 3;
int **nums;
cout << "Creating arrays...";
nums = new int*[max]; // <<---- not: nums = new int[max];
for(size_t i = 0; i < max; ++i)
nums[i] = new int(i);
cout << "done" << endl;
cout << "Contents: ";
for(size_t i = 0; i < max; ++i)
cout << *nums[i] << ' '; // <<---- dereferenced twice to reach actual value
cout << endl;
cout << "Deleting arrays...";
for(size_t i = 0; i < max; ++i)
delete nums[i];
delete[] nums;
cout << "done" << endl;
return 0;
}
请注意,这与前面描述的情况相同。要运行它,请将代码放入名为 test.cpp 的文件中并使用以下 (GNU/Linux) 命令:
➜ /tmp g++ test.cpp -o test && ./test
Creating arrays...done
Contents: 0 1 2
Deleting arrays...done
➜ /tmp
如果您想在调试器中检查它,请将 -ggdb 添加到上面的 g++ 命令中,以确保将调试符号添加到二进制文件中。然后您可以使用b <linenumber>(例如b 10)设置断点并使用p <variable_name>(例如p nums、p *nums等)打印地址和值。
但同样,您不需要像这样使用原始指针。您可以而且应该使用标准模板库中的容器。
重构您的代码
我重写了下面的示例代码,使用 std::vector 而不是双指针。
#include <iostream>
#include <vector>
using namespace std;
class BankTeller
{
public:
BankTeller() {
cout << "Created BankTeller\n";
}
~BankTeller() {
cout << "Destroyed BankTeller\n";
}
};
class BankModel
{
public:
BankModel(size_t count) {
// remember to throw exception if count <= 0
for(size_t i = 0; i < count; ++i)
_tellers.push_back(new BankTeller());
cout << "Created BankModel\n";
}
~BankModel() {
// consider using iterators
for(size_t i = 0; i < _tellers.size(); ++i) {
delete _tellers[i];
_tellers[i] = 0;
}
_tellers.clear();
cout << "Destroyed BankModel\n";
}
private:
vector<BankTeller*> _tellers;
};
int main() {
BankModel *model = new BankModel(5);
delete model;
return 0;
}
在我的系统 (GNU/Linux) 中构建和运行它如下所示:
➜ /tmp g++ tellers.cpp -o tellers
➜ /tmp ./tellers
Created BankTeller
Created BankTeller
Created BankTeller
Created BankTeller
Created BankTeller
Created BankModel
Destroyed BankTeller
Destroyed BankTeller
Destroyed BankTeller
Destroyed BankTeller
Destroyed BankTeller
Destroyed BankModel
希望这能帮助您理解指针和使用 STL 的好处。