Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Creating a dangling const pointer is pretty trivial. Hell, make it a const reference.

    #include <iostream>

    struct Foo {
        const int &dangling;

        Foo(const int &dangling): dangling(dangling) { }
    };

    Foo foo() {
        int dangling = 0;
        Foo foo(dangling);
        return foo;
    }

    int main() {
        std::cout << foo().dangling << std::endl;
        return 0;
    }

Neither g++ nor clang warn on this, either. I am not sure why you think const pointers are safe. They aren't. Flat out.


Well I was assuming for pointers that they'd be initialised to something sensible. That would be a coding standard problem if they're not.

The example you give is also a problem with coding standards, I'd argue. It isn't the languages fault that you're using a reference that's going out of scope - that's just bad coding. (A pointer going out of scope isn't so bad, no?)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: