#include <iostream>
#include <limits>
#include <stdexcept>
using std::clog;
namespace{
class FloatValue
{
public:
FloatValue() : m_amount(0.0f)
{
clog << "Creating default floating point value.\n";
}
explicit FloatValue(float amount) : m_amount(amount)
{
clog << "Creating floating point value with amount " << m_amount <<
".\n";
if(std::numeric_limits<float>::infinity() == m_amount){
throw std::domain_error("Floating point value cannot be infinite");
}
}
private:
float m_amount;
};
} // namespace
int main()
{
constfloat INFINITE_VALUE = std::numeric_limits<float>::infinity();
try{
FloatValue(INFINITE_VALUE);
}
catch (const std::domain_error& error) {
std::cerr << error.what() << std::endl;
}
return 0;
}
should print:
Creating floating point value with amount inf
Floating point value cannot be infinite
However when compiling the code the complier issues a warning like:
TestFloatValue.cpp: In function ‘int main()’:
TestFloatValue.cpp:34: warning: unused variable ‘INFINITE_VALUE’
and during execution, the output is:
Creating default floating point value.
What is needed so the code will behave as expected?
Seems that it is creating a FloatValue object called INFINITE_VALUE in the try scope
Try adding an object name at line 35 or make a function returning an unnamed object