两个简化的示例:
#include <cstdlib>
#include <string>
#include <vector>
class Object{};
void use1(Object * o)
{
(void)(o);
}
void use2(std::string & s)
{
(void)(s);
}
int f1()
{
Object * object_ptr{ nullptr };
{
Object object{};
object_ptr = &object;
}
use1(object_ptr); // UB
return rand();
}
int f2()
{
std::vector<std::string> v{"foo", "bar"};
auto & v_ref = v[0];
v.emplace_back("baz");
use2(v_ref); // UB
return rand();
}
int main()
{
return f1() + f2();
}
(rand()
仅用于测试。)
Rust 无法编译这样的源代码。使用 Clang 或 GCC(或者可能是 MSVC?)是否有一个选项可以检测这种未定义的行为?
最佳答案
开箱即用,不,你不能。 C++ 不像 Rust 那样会给你搬起石头砸自己脚的权力。
幸运的是,静态分析器可以为您检测错误。借助 clang 静态分析器,生命周期检查器肯定即将出现 link to the mailing list message并且可能适合您的需求。
如果你有内存错误,你可以用 valgrind 检测它们,它对我来说有时很有用。
关于c++ - 像 Rust 一样检测 UB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34722647/