9
I’m doing a project that implements a Python-style console. It has several functions, it has many things. But I need to implement a command called set
. set
declare a character string and define its value as defined by the user.
class Variavel
{
private:
char* nome;
char* valor;
public:
Variavel() : nome(NULL), valor(NULL)
{
}
~Variavel()
{
delete[] nome;
delete[] valor;
}
void DefVar(const char* valor, const char* nome)
{
this->valor = new char[strlen(valor)];
this->valor = const_cast<char*>(valor);
this->nome = new char[strlen(nome)];
this->nome = const_cast<char*>(nome);
}
};
I could create a large array or pointer, and with each instance the client defines one more variable, the number of the array increases. When he asked for a variable, he would map each array to the end. It is a method that works, but is very slow, uses a lot of memory and is a little inefficient. How to create a Runtime variable in an efficient way?
Improved with the constructor and destructor, but you still have to disable the copy constructor, or implement one, otherwise you will end up with two objects pointing to the same buffers, which will generate
delete's
duplicated. Hence thestd::string
is more practical, as already commented.– C. E. Gesser
And there is one more reason for you to use Std::string. Your Defvar function is with memory Leak. You are setting value and name without releasing what value and name already held.
– Lucas Lima