Ksamp
Ksamp

Reputation: 139

Variable loose it's value

I've met the following issue. I have some classes:

class classA
{
public:
    std::vector< classB > elementsOfBClass;
}

classA::classA()
{
    int a = 1;
    int b[2] = {2,3};
    elementsOfBClass.pushBack(classB(a,b));
}

class classB
{
public:
    int a;
    int* b;

    classB(int a, int* b);
};

classB::classB(int aVal, int* bVal)
{
    a = aVal;
    b = bVal;
    LOG("%d",a);  // a=1 
    LOG("%d,%d",b[0],b[1]); //b[0] = 2 , b[1] = 3
    //If I output b[0] and b[1] here then it's ok
}

And also I have some code that uses this class:

classA classAObject = classA();
LOG("%d", classAObject.elementsOfClassB[0].a);  // a=1
LOG("%d,%d",classAObject.elementsOfClassB[0].b[0],classAObject.elementsOfClassB[0].b[1]); //Here is some strange issue. b[0] and b[1] is always some absolutely random values!

b[0] and b[1] is some strange values. Can you please help me to understand why?

Thank you!

Upvotes: 0

Views: 104

Answers (2)

informaticienzero
informaticienzero

Reputation: 1867

If you have choice, use smart pointers and std::containers such as std::array (if size is known at compile-time, C++11 required) or std::vector. It will save you from headaches.

Upvotes: 0

marom
marom

Reputation: 5230

Your classB::b member does not make a copy of b, simply takes a pointer to a variable allocated on the stack. That gets overwritten when ClassA contructr exits.

Your classB should hold a member declared as b[2] ad make a deep copy of int *bVal

Upvotes: 3

Related Questions