何时在作用域中评估assert()表达式?
我试图理解assert()C++ 中的宏,但我对何时检查断言语句的有效性感到困惑。我创建了一个 Pyramid 类,我想在其中检查 Class 属性是否为正,因此我首先创建了一个try() -> catch()异常处理,如果我为实例化 Pyramid 对象输入一个负值,它会抛出错误(以及printData()正在评估的错误)
然而,我assert()也是通过在 中放置一个语句caught=false来实现caught() { }的,无论是表达式std::cout<<errorText还是printData()被评估,程序都只是抛出一个Assertion "caught" failed.错误。
有人可以解释,当我们把一个如何控制执行assert()的范围说明,为什么std::cout<<errorText在也printData()都没有得到评估?代码如下:
#include <stdexcept>
#include <iostream>
#include<string>
using namespace std;
class Pyramid
{
private:
int length;
int width;
int height;
float volume;
public:
Pyramid(int l, int w, int h) : length(l), width(w), height(h)
{
volume = (1.0f / 3) * length * width * height;
}
void printData() const
{
std::cout << "nLength : " << length
<< "nWidth : " << width
<< "nHeight : " << height
<< "nVolume : " << volume;
}
int Length() const
{
return length;
}
int Height() const
{
return height;
}
int Width() const
{
return width;
}
float Volume() const
{
return volume;
}
};
int main()
{
bool caught{true};
try
{ //Initialize Pyramid
Pyramid pyramid( -11, 2, 3);
//Print Check Pyramid Attributes
pyramid.printData();
//Check for validity of attributes
if (pyramid.Length() <= 0 || pyramid.Width() <= 0 || pyramid.Height() <= 0)
throw std::string("nAttributes cannot be zero or negative");
}
catch (std::string errorText)
{
std::cout << errorText;
caught = false;
}
assert(caught);
return 0;
}
回答
何时在作用域中评估 assert ( ) 表达式?
assert在执行到达时进行评估。与大多数表达式语句相同(assert本身是一个宏,但它会扩展为表达式语句)。
表达式 std::cout<<errorText 和 printData() 都没有被评估
你猜错了。他们将得到评估。
相反,可能会发生的情况是,因为程序终止,所以没有清理静态对象。并且因为没有清理,std::cout所以没有被销毁。并且因为std::cout没有被销毁,您插入的输出不一定刷新到标准输出流,而是保留在std::cout. 在这种情况下,您不会在终端中看到输出。