Replacing auto_ptr in VC++ 8

后端 未结 7 1475
Happy的楠姐
Happy的楠姐 2021-02-14 17:31

std::auto_ptr is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows auto_ptr x = new T();, which of cour

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 17:45

    Not an answer, but for general interest of anyone for whom these bugs are relevant. There's one more related bug with VC8's auto_ptr, which has to do with implicit upcasts. It's probably the most evil of the bunch, because other bugs just let you compile code that is otherwise illegal according to Standard without failing, but at least compliant code works fine. With this bug, the code that is actually compliant does not work properly.

    The problem is this. Standard specifies auto_ptr constructors and conversion operators in such a way that they support implicit upcasting of auto_ptrs, just as with normal pointers. However, VC8 implementation of that does a reinterpret_cast rather than a static_cast there. Naturally, not only this is U.B. by the letter of the standard, but it also breaks with multiple base classes and/or virtual inheritance. Here's an example of legal code broken by this:

    struct Base1 { int x; };
    struct Base2 { int y; };
    struct Derived : Base1, Base2 {};
    
    std::auto_ptr createDerived()
    {
      return std::auto_ptr(new Derived);
    }
    
    std::auto_ptr base2(createDerived());
    

    At one of my past jobs, when we ran into this problem in production, we ended up simply patching the headers ourselves (it's a trivial 2-line fix).

提交回复
热议问题