What is the best way to store a reference in an object?

5

Suppose I want to create a library where an object should receive another object added by the user and store for later use. Ex:

//header.h
class Caixa{
private:
   Botao botoes[5];
public:
   void addBotao(Botao botao){
      int i;
      while(botoes[i]!=NULL)
         i++;
      botoes[i] = botao;
   }
   Botao getBotao(int i){
      return botoes[i];
   }
}

class Botao{
private:
   char nome[10];
public:
   void Botao(char texto[10]){
      nome = texto;
   }
}

//main.cpp
void main(){
   Caixa caixa1 = Caixa();
   Botao botao1 = Botao("clique");
   caixa1.addBotao(botao1);
}

For reasons of memory economy it would be interesting to pass this object by reference. But, considering which references should be referenced at startup, it seems to me that it would not be possible to store the reference in the object, right? Using pointers to make the passage, I would not be sure that the variable would still be there when I was to use it. Can you tell me the best way to solve this problem?

    
asked by anonymous 21.11.2015 / 13:53

1 answer

5

Do you want to learn the right way or the way gambiarra? I'll definitely go.

So I modernized your code using C ++ 11/14. Do not mix C with C ++. And if you're going to use C ++, use the more modern features unless you have a constraint on the project you're working on (which does not seem to be the case).

Some things may be slightly different depending on intent. I would probably avoid shared_ptr and try to use unique_ptr or reference_wrapper . And I would probably use emplace_back() instead of push_back , so I would not need to create the object separately, but it depends on what you want.

You can store the reference, but it would probably be an error. With raw pointers it's a problem, but with managed pointers you can have "security".

#include <string>
#include <vector>
#include <memory>
using namespace std;

class Botao {
private:
   string nome;
public:
   Botao(string texto) {
      nome = texto;
   }
};

class Caixa {
private:
   vector<shared_ptr<Botao>> botoes;
public:
   void addBotao(shared_ptr<Botao> botao) {
      botoes.push_back(botao);
   }
   shared_ptr<Botao> getBotao(int i) {
      return botoes[i];
   }
};

int main() {
   auto caixa1 = Caixa();
   auto botao1 = make_shared<Botao>("clique");
   caixa1.addBotao(botao1);
   return 0;
}

See running on ideone .

    
21.11.2015 / 14:41