Discussion: Never let a pointer outlive the object it points to
讨论:切勿让指针的生命周期超出其指向的对象
Reason(原因)
To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
避免极难发现的错误。 防止引用此类指针未定义、并可能导致破坏类型安全系统的行为。
Example(例)
string* bad() // really bad
{
vector<string> v = { "This", "will", "cause", "trouble", "!" };
// leaking a pointer into a destroyed member of a destroyed object (v)
return &v[0];
}
void use()
{
string* p = bad();
vector<int> xx = {7, 8, 9};
// undefined behavior: x might not be the string "This"
string x = *p;
// undefined behavior: we don't know what (if anything) is allocated a location p
*p = "Evil!";
}
The strings of v are destroyed upon exit from bad() and so is v itself. The returned pointer points to unallocated memory on the free store. This memory (pointed into by p) might have been reallocated by the time *p is executed. There might be no string to read and a write through p could easily corrupt objects of unrelated types.
v的字符串s在bad退出时被销毁,v本身也被销毁。返回的指针指向自由存储中的未分配内存。在执行* p时,该内存(由p指向)可能已经被重新分配。可能没有要读取的字符串,并且通过p进行的写入很容易损坏无关类型的对象。
Enforcement(实施建议)
Most compilers already warn about simple cases and have the information to do more. Consider any pointer returned from a function suspect. Use containers, resource handles, and views (e.g., span known not to be resource handles) to lower the number of cases to be examined. For starters, consider every class with a destructor as resource handle.
大多数编译器已经可以警告一些简单的情况,并提供更多信息。考察从函数返回的任何可疑指针。使用容器,资源句柄和视图(例如,span已知不是资源句柄)来减少要检查的需求量。对于初学者,请将具有析构函数的每个类视为资源句柄。
原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-never-let-a-pointer-outlive-the-object-it-points-to