gpt4 book ai didi

c++ - 如果在 GCC 4.4.7 上未使用返回值,则强制调用类 operator== 失败

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:31 24 4
gpt4 key购买 nike

我想知道是否有一种方法可以将类上的 operator== 的使用转换为编译器错误,如果结果没有对结果进行任何操作。原因是在开发人员打算使用 operator= 时捕捉到对 operator== 的使用。

我不关心解决方案是否特定于 GCC,只要它适用于 GCC 4.4.7。解决方案可以包括特定于 GCC 的属性、编译器编译指示或对下面给出的 C++ 类的源代码文件更改。不太吸引人的是对编译器选项的更改。

请参阅下面的示例。取消注释下面的 #define DO_STRING_LITERAL_TEST 行,您将看到来自编译器的有用消息:

/usr/bin/g++  -MD -DDEBUG -g -ggdb -gstabs+ -O0  -fPIC  -Wall -Werror -Wsynth -Wno-comment -Wreturn-type   main.cpp -c -o main.o
cc1plus: warnings being treated as errors
main.cpp: In function ‘int main(int, char**, char* const*)’:
main.cpp:37: error: comparison with string literal results in unspecified behaviour

注释 #define DO_STRING_LITERAL_TEST 行,然后取消注释 #define DO_STRING_CONTAINER_TEST 行。这编译得很好,我希望它在指示的行上失败:

foo == " "; // <-- I need this to throw a compiler error

示例代码如下:

#include <iostream>
#include <string>

class StringContainer {
private:
std::string _val;

public:
StringContainer(const char * inString = NULL) : _val(inString ? inString : "") {}

bool operator==(const StringContainer & other) const
{
return _val == other._val;
}

void operator=(const char * other)
{
_val = other;
}

const char * getString() const
{
return _val.c_str();
}

};

int main(int argc, char *argv[], char *const envp[])
{
std::cout << __FILE__ << ":" << __LINE__ << ":" << "main begin" << std::endl;

#define DO_STRING_LITERAL_TEST
#ifdef DO_STRING_LITERAL_TEST
const char * invalidval = "foo bar";
// The following use of == throws a nice compiler error on GCC 4.4.7:
invalidval == " ";
#endif // DO_STRING_LITERAL_TEST


//#define DO_STRING_CONTAINER_TEST
#ifdef DO_STRING_CONTAINER_TEST
StringContainer foo;
foo = "some string";
foo == " "; // <-- I need this to throw a compiler error
std::cout << __FILE__ << ":" << __LINE__ << ":" << "foo contains <" << foo.getString() << ">" << std::endl;
#endif // DO_STRING_CONTAINER_TEST


std::cout << __FILE__ << ":" << __LINE__ << ":" << "main end" << std::endl;
return 0;
} // end main

一个非常接近的答案是 https://stackoverflow.com/a/12416677/257924 .但这指定了函数属性的使用,这看起来很有吸引力,但是我需要使用的 GCC 编译器版本在使用 -Werror=unused-result 时停滞不前:

cc1plus: error: -Werror=unused-result: No option -Wunused-result

如果有一个仅源代码的更改,暂时(可能是某些代码段)unused-result 警告,那就更好了。 https://freeswitch.org/jira/browse/FS-6850#commentauthor_55299_verbose显然表明“与 gcc 4.8.3 的相同测试通过正常,因为它支持参数。”

最佳答案

这不应该是您在代码中验证的内容。这应该是你的编译器会为你做的事情。如果您需要 std::string,您应该使用 std::string - 而不是 MyStringThatHasThisExtraEqualityCheck

我建议以下几件事之一:

  • 窃听您最喜欢的 gcc 开发人员,让他们根据 this bug report 实现 -Wunused-comparison
  • 只需使用支持该警告的 clang 编译您的代码。然后您可以添加 -Werror 使其成为错误。您不需要运行 clang 二进制文件,但额外的正交不会有什么坏处(只是给了您更多使用 slack off 的借口)。
  • 使用一些外部静态分析工具为您验证这些东西。
  • 编写单元测试。

关于c++ - 如果在 GCC 4.4.7 上未使用返回值,则强制调用类 operator== 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35634648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com