【问题标题】:How to write a constructor with exception如何编写有异常的构造函数
【发布时间】: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 &gt; 0 &amp;&amp; width &gt; 0,代码是if ( height &gt; 0 &amp;&amp; width &gt; 0 )...但我怀疑这不是你要问的...
  • 您可以挑选一些东西,例如负尺寸或明显太大的尺寸,但归根结底,它们唯一可靠地检测内存不足情况的方法是内存不足.即使您查询系统以获得最大的可用空闲块,也没有好的方法可以保证在测试和请求之间没有其他人占用或缩小该空闲块。
  • @user4581301:这是特定于平台的,而且非常先进,因为我怀疑是对构造函数/异常机制的一些细节的简单混淆......
  • 什么是平台特定的,我说的东西无论如何都不值得尝试?

标签: c++ exception constructor


【解决方案1】:

如何在初始化需要分配的数据之前检查是否height&gt;0&amp;&amp;width&gt;0

使用函数:

class Game
{ 
    // ...
    static Matrix<std::shared_ptr<Character>>
    init_data(int height, int width)
    {
        if (height <= 0 || width <= 0)
            throw std::runtime_error("naughty dimensions");
        return {height, width};
    }
    
    
public:
    Game(int height, int width) :
        data(init_data(height, width)),
        height(height),
        width(width)
    {}

这样,除非提供的维度有效,否则成员永远不会被初始化。


其他注意事项:

  • 诸如Matrix 中的那些裸拥有指针是不好的。你应该避免它们。使用它们的一个后果是 Matrix 的协程函数不是异常安全的。如果创建 Ts 抛出,它将泄漏内存。
  • 在Matrix 和Game 中存储维度似乎是多余的。

【讨论】:

    【解决方案2】:

    对于任何需要它的人来说,解决方案是:

     Game(int height, int width):data((height<=0)||(width<=0) ? throw IllegalArgument() : Dimensions(height,width))
        ,height(height),width(width)
        {
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2015-05-08
      相关资源
      最近更新 更多