wutiantong
V2EX  ›  C

请问大佬们下面这样的代码是 UB 么?

  •  
  •   wutiantong · Dec 18, 2018 · 2810 views
    This topic created in 2703 days ago, the information mentioned may be changed or developed.
    #include <iostream>
    
    template<std::size_t D>
    struct FakeNest
    {
        int & get() noexcept { return all_[0]; }
        FakeNest<D-1> &sub() noexcept { return *reinterpret_cast<FakeNest<D-1> *>(&all_[1]); }
        private: int all_[D];
    };
    
    int main()
    {
        FakeNest<4> a;
        a.sub().sub().get() = 666;
        std::cout << *(&a.get() + 2) << std::endl;
    }
    

    结果是符合预期的,但总觉得这种写法有点太作弊了,算不算 UB 呢?

    几个可能相关的 topic 是:

    1. reinterpret_cast
    2. pointer-interconvertible
    3. Standard_layout
    Supplement 1  ·  Dec 19, 2018
    我今天看了很久这方面的资料,学到了很多新的知识点。有兴趣的话不妨在这个问题上做一些深入了解。
    2 replies    2018-12-19 09:57:59 +08:00
    chinuno
        1
    chinuno  
       Dec 18, 2018 via Android
    算是 ub。看编译器实现吧。早期的 c++编译器对象模型是每个对象内存既带成员又带函数指针不能这样玩。现在的各个编译器如果不带虚函数不是虚继承基本上跟 c 结构体一样的内存分布用起来没问题,但是不能保证以后哪次更新编译器实现变了还能保持工作
    lrxiao
        2
    lrxiao  
       Dec 19, 2018
    FakeNest<D-1> 和 int 不 pointer-interconvertible 啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5493 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 08:49 · PVG 16:49 · LAX 01:49 · JFK 04:49
    ♥ Do have faith in what you're doing.