0

If I have a class:

class Model{
    Model();
};
Model model;
Model& ref=model;

and I want to store references for Model in a Vector collection, have I to declare models array as std::vector<Model> models; or std::vector<Model&> models;

Mohamed
  • 337
  • 3
  • 18
  • 3
    You can't store references in a container unless you use [`std::reference_wrapper`](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper). – πάντα ῥεῖ May 25 '17 at 09:37
  • in this case should I use std::reference_wrapper or just simply use pointer? – Mohamed May 25 '17 at 09:48
  • _"in this case"_ Which case in particular? You didn't elaborate on your use case very much. – πάντα ῥεῖ May 25 '17 at 09:50
  • Excuse me, I mean is it better storing references or pointers in a vector? – Mohamed May 25 '17 at 09:54
  • I can't say finally without knowing your particular use case. – πάντα ῥεῖ May 25 '17 at 09:55
  • I am using OpenGL so I have Model class which loads and stores data for 3D models which may be large, I put them to a vector to iterate and render them each frame (may be 60 frame per second), I create each model once so should I use pointers "i know pointer is slower than reference specially with large classes and structs and may be unsafe" or using references? – Mohamed May 25 '17 at 10:02
  • 2
    _"i know pointer is slower than reference"_ Where did you get that myth from? I'd say they are fairly the same. I'd recommend you don't have any `Models` instantiated outside of the vector, but let it be the only place where they live. Use a `std::vector>` for that, and access with raw pointers from the client code. – πάντα ῥεῖ May 25 '17 at 10:11
  • 1
    what is the feature of using std::vector> over std::vector? – Mohamed May 25 '17 at 10:29
  • 1
    Automatic dyynamic memory management. – πάντα ῥεῖ May 25 '17 at 10:29
  • I got it, thank you sir – Mohamed May 25 '17 at 10:31

0 Answers0