Why allow `propagate_on_container_swap == false` in Allocators, when it might cause undefined behaviour?

后端 未结 2 1038
庸人自扰
庸人自扰 2021-02-07 18:29

Note: Originally asked by Matt Mcnabb as a comment on Why can swapping standard library containers be problematic in C++11 (involving allocators)?.

2条回答
  •  佛祖请我去吃肉
    2021-02-07 18:47

    It is not so much that the Standard allows propagate_on_container_swap to cause Undefined Behavior, but that the Standard exposes Undefined Behavior via this value!


    A simple example is to consider a scoped allocator, which allocates memory from a local pool, and which said pool is deleted when the allocator goes out of scope:

    template 
    class scoped_allocator;
    

    Now, let us use it:

    int main() {
        using scoped = scoped_allocator;
    
        scoped outer_alloc;
        std::vector outer{outer_alloc};
    
        outer.push_back(3);
    
        {
            scoped inner_alloc;
            std::vector inner{inner_alloc};
    
            inner.push_back(5);
    
            swap(outer, inner); // Undefined Behavior: loading...
        }
    
        // inner_allocator is dead, but "outer" refers to its memory
    }
    

提交回复
热议问题