使用指针的合法旧版代码突然变成UB [英] Legal legacy code using pointers suddenly becomes UB

查看:91
本文介绍了使用指针的合法旧版代码突然变成UB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有C ++ 98的旧版代码:

bool expensiveCheck();

struct Foo;

bool someFunc()
{
    Foo *ptr = 0;
    if( expensiveCheck() )
        ptr = new Foo;

    // doing something irrelevant here
    ...
    if( ptr ) {
        // using foo
    }
    delete ptr;
    return ptr; // here we have UB(Undefined Behavior) in C++11
}

因此,基本上,这里的指针用于保留动态分配的数据,并同时将其用作标志.对我来说,这是可读的代码,我相信这是合法的C ++ 98代码.现在根据这个问题:

删除后c ++中的指针

删除后指针本身会发生什么?

此代码在C ++ 11中具有UB.是真的吗?

如果是的话,还有另一个问题,我听说委员会付出了巨大的努力,以不破坏新标准中的现有法规.如果在这种情况下我没记错的话,那不是真的.是什么原因?这样的代码是否已经被认为是有害的,所以没人在乎它会被破坏吗?他们没有考虑后果吗?这样的优化是如此重要吗?还有吗?

解决方案

您的示例在C ++ 98下也表现出未定义的行为.根据C ++ 98标准:

[basic.stc.dynamic.deallocation]/4 如果标准库中分配给释放函数的参数是不是空指针值(4.10)的指针,则释放函数应当释放指针所引用的存储,从而使所有引用已分配存储的指针无效.使用无效的指针值(包括将其传递给释放函数)的效果是不确定的.33)

脚注33)在某些实现中,它会导致系统生成的运行时错误.

Let's say we have this legacy code from C++98:

bool expensiveCheck();

struct Foo;

bool someFunc()
{
    Foo *ptr = 0;
    if( expensiveCheck() )
        ptr = new Foo;

    // doing something irrelevant here
    ...
    if( ptr ) {
        // using foo
    }
    delete ptr;
    return ptr; // here we have UB(Undefined Behavior) in C++11
}

So basically pointer here is used to keep dynamically allocated data and use it as a flag at the same time. For me it is readable code and I believe it is legal C++98 code. Now according to this questions:

Pointers in c++ after delete

What happens to the pointer itself after delete?

this code has UB in C++11. Is it true?

If yes another question comes in mind, I heard that committee puts significant effort not to break existing code in new standard. If I am not mistaken in this case this not true. What is the reason? Is such code considered harmfull already so nobody cares it would be broken? They did not think about consequences? This optimization is so important? Something else?

解决方案

Your example exhibits undefined behavior under C++98, too. From the C++98 standard:

[basic.stc.dynamic.deallocation]/4 If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.33)

Footnote 33) On some implementations, it causes a system-generated runtime fault.

这篇关于使用指针的合法旧版代码突然变成UB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆