抑制警告:未使用的变量

时间:2017-03-14 09:20:55

标签: c++ c++11 suppress-warnings

尝试使用以下命令编译我的代码: g ++ Error.cpp -Wall -std = c ++ 0x -o filename
我收到警告: Error.cpp:40:30:警告:未使用的变量'ostr'[-Wunused-variable]

我已经看到 -Wall 可以删除以禁止警告,但我不想这样做。我想在我的代码中加入一些东西来解决它。只编码了〜6个月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;
}

编辑:是第40行是if的行。出于某种原因,我曾认为const char*(ostr)会将m_message放在ostr内,然后可以将其返回并输出到其他位置。我没有意识到我只是在if语句中创建了一个无用的变量,认为我的操作符过载会发挥作用虽然我并非100%确定我是否正确使用它...

2 个答案:

答案 0 :(得分:1)

this live example所示,问题不在于函数参数ostr:返回语句使用了一个。

问题是您在ostr内声明的const char *类型的本地变量if

if (!bool(E)) { const char*(ostr); }

括号是合法的,但是多余的:该行等同于:

if (!bool(E)) { const char *ostr; }

您正在声明一个局部变量(碰巧隐藏了函数参数),并没有将它用于任何事情。

如果您要将邮件从E流式传输到ostr,则必须执行以下操作:

if (!bool(E)) { ostr << static_cast<const char*>(E); }

答案 1 :(得分:0)

你的意思是做什么?

std::ostream& ict::operator<<(ostream& ostr, const Error& E) {
    if (!bool(E)) { ostr << E.m_message; }
    return ostr;
}