【发布时间】:2016-01-11 13:22:23
【问题描述】:
两个简化示例:
#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?)是否可以选择检测这种未定义的行为?
【问题讨论】:
-
rust 的类型有 lifetime,而 c++ 没有。
-
如果您查看邮件列表,目前正在使用 clang 静态分析器进行生命周期检查:lists.llvm.org/pipermail/cfe-dev/2015-December/046653.html
-
@GuillaumeRacicot 仅检查可用工具:PVS-Studio 可以检测到第一个 UB (
V506 Pointer to local variable 'object' is stored outside the scope of this variable. Such a pointer will become invalid.),但无法检测到第二个。 cppcheck 也可以先检测到(Dead pointer usage),但不能检测到第二个。
标签: c++ gcc clang undefined-behavior compiler-options