Placement new breaks consts and references?

后端 未结 4 1909
攒了一身酷
攒了一身酷 2020-12-20 15:29

Following the discussion on my answer to this question, apparently:

the following code is allowed

struct Foo {
    int x;
};

Foo f;         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-20 16:21

    Optimization. Suppose I have:

    struct Foo
    {
        int const x;
        Foo( int init ) : x( init ) {}
    };
    
    int
    main()
    {
        Foo a( 42 );
        std::cout << a.x << std::endl;
        new (&a) Foo( 3 );
        std::cout << a.x << std::endl;
        return 0;
    }
    

    The compiler, having seen a const int object, has the right to suppose that the value doesn't change; the optimizer might simply keep the value in a register accross the placement new, and output it again.

    Note that your example is actually quite different. The data member has type int const&; it is a reference (and references are always const), so the compiler can assume that the reference always refers to the same object. (The value of this object may change, unless the object itself is also const.) The compiler can make no such assumption about the value of the object it refers to, however, since i (in your case) can clearly change. It is the fact that the reference itself (like all references) is immutable that causes the undefined behavior here, not the const that you've written.

提交回复
热议问题