EliasFarhan / NekoEngine

Generic 3d engine based on SDL2 and OpenGL ES 3/WebGL2
13 stars 5 forks source link

Passer des allocator en référence [Oleg] ? #42

Closed LoshkinOleg closed 4 years ago

LoshkinOleg commented 4 years ago

J'ai une erreur de compilation qu'il me sort lorsque j'essaye de passer une reference d'allocator au constructeur d'une FixedMap(FreeListAllocator&):

Code du TEST:

    const size_t MAP_SIZE = 4;
    const size_t BYTES = 1024;
    void* mem = malloc(BYTES + 1);

    auto allocator = FreeListAllocator(BYTES + 1, mem);
    FixedMap<unsigned int, float, MAP_SIZE> map = FixedMap<unsigned int, float, MAP_SIZE>(allocator);

Code du constructeur:

public:
FixedMap(FreeListAllocator& allocator)
    {
        allocator_ = allocator;
        pairs_.resize(Size); // Initializes the pairs to nullptr.
    }
private:
FreeListAllocator& allocator_;

Erreur:

In file included from /home/user/Desktop/NekoEngine/test/test_map.cpp:2:
/home/user/Desktop/NekoEngine/core/include/mathematics/map.h:22:5: error: constructor for 'neko::FixedMap<unsigned int, float, 4>' must explicitly initialize the reference member 'allocator_'
    FixedMap(FreeListAllocator& allocator)
    ^
/home/user/Desktop/NekoEngine/test/test_map.cpp:16:51: note: in instantiation of member function 'neko::FixedMap<unsigned int, float, 4>::FixedMap' requested here
    FixedMap<unsigned int, float, MAP_SIZE> map = FixedMap<unsigned int, float, MAP_SIZE>(allocator);
                                                  ^
/home/user/Desktop/NekoEngine/core/include/mathematics/map.h:106:24: note: declared here
    FreeListAllocator& allocator_;
                       ^

Je saisi pas pourquoi il voit pas que je suis en train de setter le field... Est-ce que j'utilise l'allocator d'une mauvaise manière?

EliasFarhan commented 4 years ago

Il faut remplacer:

public:
FixedMap(FreeListAllocator& allocator)
    {
        allocator_ = allocator;
        pairs_.resize(Size); // Initializes the pairs to nullptr.
    }

Par:

public:
FixedMap(FreeListAllocator& allocator) : allocator_(allocator)
    {
        pairs_.resize(Size); // Initializes the pairs to nullptr.
    }
LoshkinOleg commented 4 years ago

Ah ouaip, en effet. Pourquoi au fait il saisi pas qu'on initialise la variable si c'est dans le body de la fonction au fait?

EliasFarhan commented 4 years ago

C'est parce que le fait de setter la valeur dans le corps du constructeur n'est pas explicite.

LoshkinOleg commented 4 years ago

Ouaip juste. Au fait avec la 1ere methode on peux faire:

FixedMap(FreeListAllocator& allocator)
    {
        allocator_.someField = 3; // Accessing nullptr!
        allocator_ = allocator;
    }

Alors qu'avec la 2ème methode ya pas moyen de glisser du code entre l'appel du constructeur et l'initialisation de allocator_ .