c++ - 像 Rust 一样检测 UB

标签 c++ gcc clang undefined-behavior compiler-options

两个简化的示例:

#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/

相关文章:

linux - 在 linux 上使用私有(private) C++ 运行时库

c++ - 尝试使用Windows Midi API时出现gcc错误

c++ - TGridOptions 上二进制表达式的无效操作数

c - 结构分配 : segment fault 11

c++ - 使用整数的最佳方法?

c++ - 使用 OpenCV 对图像产生涡旋效应

c++ - 矩阵乘法性能 numpy 和 eigen c++

c - 如何计算未知位数的整数类型的汉明权重(又名人口计数,即整数中 1 的位数)?

c++ - 我不能将大小为 8 字节的类类型转换为 uint64_t 吗?

debugging - 使用CLANG进行编译时,是否有等效的GDB for GCC进行调试?