我最近被这个震惊了:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<string, string> strings;
strings["key"] = 88; // surprisingly compiles
//map<string, string>::mapped_type s = 88; // doesn't compile as expected
cout << "Value under 'key': '" << strings["key"] << "'" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它打印'X',即ASCII为88.
为什么字符串映射接受int作为值?map的文档operator[]说它返回的mapped_type&是string&这种情况,它没有隐式转换int,是吗?
在最近的一次bug搜索中,我发现了一个返回指向临时变量成员的指针的问题.违规(简化)代码是:
struct S {
S(int i) : i(i) {}
int i;
int* ptr() { return &i; }
};
int* fun(int i) { return S(i).ptr(); } // temporary S dies but pointer lives on
int main() {
int* p = fun(1);
return *p; // undefined
}
Run Code Online (Sandbox Code Playgroud)
怎么预防这个?海湾合作委员会和铿锵有-Waddress-of-temporary,-Wreturn-stack-address但他们似乎因为ptr()肮脏的行为充当中间人而松散.它们仅在直接获取指针时触发:
int* fun(int i) { return &S(i).i; } // rightly fails to compile
Run Code Online (Sandbox Code Playgroud)
我的项目还将cppcheck整合到持续集成中,但它也无法获取(在这里提出).
哪种静态分析工具可以防止这类错误?
编辑:GCC确实从版本6.1.0开始接收-Wreturn-local-addr并且(令人惊讶地)-O2开启.
是否可以在C中编译时对元素进行排序?
语法是次要的,我正在考虑这样的宏:
SORT(9, -1, 12, 4) // expands to: -1, 4, 9, 12
SORT(dog, cat, cow) // expands to: cat, cow, dog
Run Code Online (Sandbox Code Playgroud)
但是我不会对任何API皱眉,只要它排序而不发出单个CPU指令.
要求非常宽松:
sort或自制的代码生成器不受欢迎,因为它们使构建步骤复杂化.SORT_5sort 5元素才行.我意识到解决方案可能会使用一些几乎没有编译的语言巫术,我只是想知道它是否可能.