The reason I cant store them as Block& is because that makes a copy of the Block when it is entered,
Raw pointers should be avoided when possible.
I'm not sure exactly what you mean by 'makes a copy'. Containers themselves can't store raw references. Possibly you are making a function accepting a ref but then putting them into a container with a non-ref.
In C++11 (which I recommend using unless you have compiler restraints) you can also store references in a container with a std::ref or std::cref. You will need to make sure your compiler is compiling in C++11 mode.
#include <iostream>
#include <map>
#include <functional>
using namespace std;
class Block {
public:
Block(const std::string& name, const int block_id) {
this->name = name;
this->block_id = block_id;
}
private:
std::string name;
int block_id;
};
const Block block_1("Vacuum", 0);
int main(int argc, char* argv[]) {
std::map<int, std::reference_wrapper<const Block>> array;
array.insert(std::pair<int, reference_wrapper<const Block>>(0, block_1));
}
Otherwise you could make your own simple ref container:
class BlockRef {
public:
BlockRef(const Block& block;blockref): blockref_(blockref) {}
operator const Block& () const { return this->blockref_; }
private:
const Block& blockref_;
};
You could also make a more advanced one with templates that's generic for any type.
Boost has them also if you are ok with using a library.