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

Asked

Viewed 248 times

5

Suppose I want to create a library, where an object should receive another object added by the user and store it 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 saving it would be interesting to pass this object by reference. But, considering that references should be referenced in the initialization, it seems to me that it would not be possible to store the reference in the object, right ? Using pointers to do the crossing, I would have no assurance that the variable would still be there when I went to use it. Can you tell me the most appropriate way to solve this problem ?

1 answer

5


Do you want to learn the right way or the right way? I’m going for the right.

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 most modern features unless you have a constraint on the project you’re working on (which doesn’t seem to be the case).

Some things may be a little different depending on the intention. I would probably avoid the shared_ptr and would try to use the unique_ptr or reference_wrapper. And I’d probably use the emplace_back() in place of push_back, so you wouldn’t need to create the object separately, but it depends on what you want.

It is possible to store the reference, but it would probably be a mistake. With raw pointers is 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.