微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

何时在作用域中评估 assert ( ) 表达式?

如何解决何时在作用域中评估 assert ( ) 表达式?

我试图理解 C++ 中的 assert() 宏,但我对何时检查断言语句的有效性感到困惑。 我创建了一个 Pyramid 类,我想在其中检查 Class 属性是否为正,因此我首先创建了一个 try() -> catch() 异常处理,如果我输入一个负值来实例化一个 Pyramid 对象,它会抛出错误(以及printData() 也在评估中)

然而,我也通过在 assert() 中放置一个语句 caught=false获取 caught() { },表达式 std::cout<<errorTextprintData() 都不会被求值,并且程序只是抛出一个 Assertion "caught" Failed. 错误

有人可以解释一下当我们在作用域中放置 assert() 语句时控件是如何执行的,以及为什么 std::cout<<errorTextprintData() 根本没有得到评估吗? 代码如下:

#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

你猜错了。他们将得到评估。

可能会发生的情况是,因为程序终止了,所以没有清理静态对象。由于没有清理,std::cout 不会被销毁。并且因为 std::cout 没有被销毁,您插入的输出不一定会刷新到标准输出流,而是保留在 std::cout 的缓冲区中。在这种情况下,您将不会在终端中看到输出。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。