简体   繁体   中英

stl container of references C++11

I know this question was asked a million of times. And most of answers just says that object should be CopyAssignable and CopyConstructible. But documentation clearly says this is the rule (until C++11) ! But still it doesn't work. Why?

Yes, the requirements are less strict now. However, right below the part you're referencing, the linked documentation clearly states that:

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements. (since C++11)

References don't meet the requirements of Erasable, therefore they still can't work.

The rules apply until C++11. In C++11 is required that element type is a complete type and meets the requirements of Erasable in which case references are not.

However you can use std::reference_wrapper to wrap your references and store them in a vector.

std::vector<std::reference_wrapper<T>> vector_of_references;

C++11 relaxed the container requirements so that non-CopyConstructible types can be used in containers, as long as you avoid operations that would need to copy the elements.

That doesn't mean that references are allowed though, just because one rule is relaxed doesn't mean that absolutely any type can be put in a container.

As the cppreference page you quoted says for C++11

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable , but many member functions impose stricter requirements.

Erasable requires that this is valid:

allocator_traits<A>::destroy(m, p)

The Allocator requirements in 17.6.3.5 [allocator.requirements] say allocators deal with any non-const object type and references are not object types, so you cannot allocate or deallocate a reference, and therefore you cannot put them in containers.

§ 23.2.1 [container.requirements.general] ¶ 1 of N4140 says (emphasis mine):

Containers are objects that store other objects . They control allocation and deallocation of these objects through constructors, destructors, insert and erase operations.

But a reference is not an object so you cannot put it into a standard library container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM