Home > Backend Development > C++ > Why Can't I Use References as Elements in a Standard Vector?

Why Can't I Use References as Elements in a Standard Vector?

DDD
Release: 2024-12-26 16:13:13
Original
876 people have browsed it

Why Can't I Use References as Elements in a Standard Vector?

Why Won't My Vector Accept References?

Problem: Vector works, but Vector causes compiler errors.

Explanation:

Vectors and other containers require their component types to be assignable. A reference is a non-assignable type because it holds a constant reference to a specific memory location. Once a reference is initialized, it cannot point to a different object.

Possible Approaches:

  • Use Pointers Instead: This is the recommended option if you need to hold multiple references to different objects. Pointers can be assigned and reassigned to different memory locations.
std::vector<int*> hello;
Copy after login
  • Create a Vector of References to Objects of a Fixed Type: This approach is acceptable if all the references refer to objects of the same type that will not be assigned or modified after insertion into the vector.
struct MyStruct { int data; };

std::vector<MyStruct&> hello;
Copy after login

However, it's important to note that this strategy can lead to dangling references if the referenced objects are deleted or moved.

  • Use a Wrapper Class: You can create a wrapper class that holds a reference internally and provides an assignable interface. This allows you to use the class as a container element.
class Wrapper {
protected:
    int& _data;
public:
    Wrapper(int& data) : _data(data) {}
};

std::vector<Wrapper> hello;
Copy after login

The above is the detailed content of Why Can't I Use References as Elements in a Standard Vector?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template