How to copy (or swap) objects of a type that contains members that are references or const?

前端 未结 5 2062
生来不讨喜
生来不讨喜 2020-12-15 10:08

The problem I am trying to address arises with making containers such as an std::vector of objects that contain reference and const data members:



        
5条回答
  •  北海茫月
    2020-12-15 10:32

    This however loses the advantages of references over pointers

    There is no advantage. Pointers and reference are different, but none is the better one. You use a reference to ensure that there is a valid instance and a pointer if passing a nullptr is valid. In your example you could pass a reference and store a pointer

    struct Bar {
       Bar (Foo & foo) : foo_reference(&foo) {}
    private:
       Foo * foo_reference;
    };
    

提交回复
热议问题