Reputation: 3
I Have this sandbox code for a proyect more complicated :
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
class Table
{
friend class Variable;
public:
Variable * variables[1021];
};
class Variable
{
friend class Nodo;
public:
char clas;
Nodo * ini;
};
class Nodo
{
public:
char clas;
Variable * father;
private:
float * value;
public:
Nodo();
void set_value(float);
float * get_value();
};
Nodo::Nodo()
{
clas = ' ';
father = NULL;
value = NULL;
}
void Nodo::set_value(float m)
{
float * r = new float();
r = &m;
value = (float *)r;
}
float * Nodo::get_value()
{
return this->value;
}
And this is the main:
void main ()
{
Nodo * n = new Nodo(); // OK.
n->set_value(5.3442); // Ok.
Variable * v = new Variable(); // This is the problem.
// When I declare another pointer an initilized it, n lost the value stored in value.
Variable * v0 = new Variable(); // Here the same.
v->ini = n;
n->father = v;
Table * t = new Table();
t->variables[0] = v;
v0 = t->variables[0];
cout << *(static_cast<float *>(v0->ini->get_value())) << endl;
}
How can I stock the value in the pointer without change? It seems that I should use const, or something similar, but I don't know how. Declaring the field value as private doesn't help. The idea is replace value with a void * later, to store any king of basic date not only float data.
Thanks!
Upvotes: 0
Views: 800
Reputation: 49986
This looks wrong:
void Nodo::set_value(float m)
{
float * r = new float();
r = &m;
value = (float *)r;
}
r
is assigned pointer to m
which is a temporary, this pointer will be invalid once set_value
finishes. Also you overwrite r value, so you have a leak here. The correct version would be:
void Nodo::set_value(float m)
{
float * r = new float();
*r = m;
value = r;
}
btw. I am not digging deeper in your code, ...
Upvotes: 1