Trying to compile my code with the following command:
g++ Error.cpp -Wall -std=c++0x -o filename
I get a warning: Error.cpp:40:30: warning: unused variable ‘ostr’ [-Wunused-variable]
I've seen that the -Wall can be removed to suppress warnings but i don't want to do that. I want to put something in my code to work around it. Only been coding for ~6 months btw.
// Error.cpp
#define _CRT_SECURE_NO_WARNINGS
// Tried using #define _CRT_UNUSED then doing _CRT_UNUSED(ostr) down below
#include <iomanip>
#include <iostream>
#include <cstring>
#include "Error.h"
void Error::message(const char* errorMessage) {
clear();
m_message = new char[strlen(errorMessage) + 1];
strcpy(m_message, errorMessage);
}
void Error::operator=(const char* errorMessage) {
message(errorMessage);
}
Error::operator const char*() const {
return m_message;
}
Error::operator bool() const {
return m_message == nullptr;
}
std::ostream& ict::operator<<(ostream& ostr, const Error& E) {
(void)ostr; // This didn't work, i still get the warning with or without it
if (!bool(E)) { const char*(ostr); }
return ostr;
}
EDIT: Yes line 40 is the line with the if. For some reason i had thought that const char*(ostr)
would place m_message
inside ostr
and then it could be returned and outputted elsewhere. I didn't recognize that i was just creating a useless variable in the if statement, thought my operator overload would come into play though i'm not 100% sure if i'm using it correctly...
As this live example shows, the problem is not the function parameter ostr
: that one is used by the return statement.
The problem is the local variable ostr
of type const char *
which you're declaring inside the if
:
if (!bool(E)) { const char*(ostr); }
The parentheses are legal, but redundant: that line is equivalent to this:
if (!bool(E)) { const char *ostr; }
You're declaring a local variable (which happens to hide the function parameter), and not using it for anything.
If you want to stream the message from E
into ostr
, you'll have to do this:
if (!bool(E)) { ostr << static_cast<const char*>(E); }