考虑以下程序:
#include <iostream> int main() { int b=3; int* a=&b; std::cout<<*a<<'\n'; delete a; // oops disaster at runtime undefined behavior }好的,根据C ++标准,程序的行为是不确定的。 但我的问题是为什么它没有定义? 为什么C ++的实现不提供任何编译器错误或任何警告? 是否真的很难确定指针的有效性(意味着检查指针在编译时是否由new返回?)是否有任何开销用于静态确定指针的有效性(即编译时间)?
Consider following program:
#include <iostream> int main() { int b=3; int* a=&b; std::cout<<*a<<'\n'; delete a; // oops disaster at runtime undefined behavior }Ok, behavior of program is undefined according to C++ standard. But my question is why it is left undefined? Why implementations of C++ don't give any compiler errors or any warnings? Is it really hard to determine validity of pointer (means to check whether pointer is returned by new at compile time?) Is there any overhead involved to determine validity of pointer statically (i.e. compile time)?
最满意答案
在编译时不可能确定指针指向什么,下面是一个例子来说明这一点:
volatile bool newAlloc; int main() { int b=3; int* a; if(newAlloc) { a = new int; } else { a = &b; } std::cout<<*a<<'\n'; delete a; // impossible to know what a will be }It is impossible to determine what a pointer points to at compile time, here is an example to illustrate this:
volatile bool newAlloc; int main() { int b=3; int* a; if(newAlloc) { a = new int; } else { a = &b; } std::cout<<*a<<'\n'; delete a; // impossible to know what a will be }更多推荐
发布评论