Home  >  Article  >  Backend Development  >  Will Polymorphism Work with Vector References in C ?

Will Polymorphism Work with Vector References in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 12:21:30820browse

Will Polymorphism Work with Vector References in C  ?

Polymorphism and Vector References in C

When working with vectors and polymorphism in C , one may encounter a situation where the stored object's type is crucial. Consider the following example:

<code class="cpp">struct Instruction { virtual void execute() { } };
struct Add : public Instruction { int a, b, c; Add(int x, int y, int z) { a = x; b = y; c = z; } void execute() { a = b + c; } };

vector<Instruction> v;
Instruction* i = new Add(1, 2, 3);
v.push_back(*i);</code>

In this code, a vector of base class objects is created, and an object of a derived class (Add) is pushed into the vector as a reference. The concern arises when accessing the "execute" function on this object:

<code class="cpp">auto ins = v.back();
ins.execute(); // Will the object retain its Add type?</code>

Will Polymorphism Work?

No, it won't. The vector stores values, not references. Therefore, when the Add object is pushed into the vector, it will be copied, resulting in an object of type Instruction, not Add.

Reference_wrapper

To ensure the polymorphism remains intact, one approach is to use std::reference_wrapper, which stores references to objects instead of objects themselves. This can be implemented as follows:

<code class="cpp">vector<std::reference_wrapper<Instruction>> ins;</code>

Preventing Memory Leaks

Additionally, the code allocates an Add object dynamically with new without deleting it, causing a memory leak. To rectify this, the code should use a smart pointer, such as std::unique_ptr, or manually delete the object before it goes out of scope.

The above is the detailed content of Will Polymorphism Work with Vector References in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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