EliasFarhan/NekoEngine

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

Closed this issue · 4 comments

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?

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.
    }

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?

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_ .