【发布时间】:2020-10-23 06:29:00
【问题描述】:
我想知道如何编写一个包含异常的构造函数
我有一堂课Character
和另一个班级Matrix<T>
template<class T>
class Matrix
{
T** data;
int col;
int row;
public:
//ctor of matrix
template<class T>
Matrix(const Matrix<T>& mat):data(new T*[mat.row]), col(mat.col), row(mat.row)
{
}
};
然后我有课游戏:
class Game
{
private:
Matrix<std::shared_ptr<Character>> data;
int height;
int width;
public:
//ctor of Game, and the one I want to know how to write
Game(int height, int width) :height(height),width(width)
{
try
{
data(Matrix<std::shared_ptr<Character>>(height,width));
}
catch(const std::badalloc&)
{
throw IllegalArgument();
}
}
我为上面Game 编写的ctor 的方式不正确,有谁知道我怎样才能正确编写它并且仍然检查它是否分配正确,
所以为了正确分配height 和width 必须大于零,但我找不到任何方法可以先检查它们然后初始化数据,这就是我尝试的原因使用try 和catch,但这是不正确的,所以有人知道编写构造函数的方法,并确保分配成功???????????????(( (使用例外)))
`
【问题讨论】:
-
我还没有弄清楚你的实际问题是什么......
-
如果你想检查
height > 0 && width > 0,代码是if ( height > 0 && width > 0 )...但我怀疑这不是你要问的... -
您可以挑选一些东西,例如负尺寸或明显太大的尺寸,但归根结底,它们唯一可靠地检测内存不足情况的方法是内存不足.即使您查询系统以获得最大的可用空闲块,也没有好的方法可以保证在测试和请求之间没有其他人占用或缩小该空闲块。
-
@user4581301:这是特定于平台的,而且非常先进,因为我怀疑是对构造函数/异常机制的一些细节的简单混淆......
-
什么是平台特定的,我说的东西无论如何都不值得尝试?
标签: c++ exception constructor