Is this using source pointers in modern bad C ++ practice?

I want to store the vector of instances of the base class without cutting objects (for example, I can also store instances of the Base child element without problems), while preserving the polymorphic behavior without adding to the list by copying values, but rather by reference.

Consider the following source file:

#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Entity
{
public:
    Entity(){this->edited = false;}
    virtual std::string name() = 0;
    bool edited;
};

class Player: public Entity
{
public:
    Player(): Entity(){}
    std::string name(){return "player";}
};

int main()
{
    std::vector<Entity*> entities;
    Player p;
    entities.push_back(&p);
    entities.at(0)->edited = true;
    Entity* ent = entities.at(0);
    std::cout << "ent = " << ent->name() << ", edited = " << ent->edited << ".\n";
    return 0;
}

I get the following output:

ent = player, edited = 1.

As the result shows (by printing the “player” and displaying the change in the “edited”), the polymorphic behavior is supported due to the raw pointer, and I can edit the list members without any problems.

, : std:: reference_wrapper ? reference_wrapper, , ? reference_wrappers , , Player, , , shared_ptr? shared_ptr - , . ?

+4
2

++. , . . - .

std::reference_wrapper<T> . , . , , .

int main()
{
    std::vector<std::reference_wrapper<Entity>> entities;
    Player p;
    entities.push_back(p);
    entities.front().get().edited = true;
    Entity & ent = entities.front();
    std::cout << "ent = " << ent.name() << ", edited = " << ent.edited << ".\n";
    return 0;
}

- , , ++. , . , ++, , . : delete, .

, std::vector<T>::front() , std::vector::at , , .

+3

. , , - Entity .

std::vector<Entity*> entities;
entities.push_back(new Player());

// Somthing that may throw exception

delete entities.at(0)

.

+1

Source: https://habr.com/ru/post/1671380/


All Articles