Majid
Majid

Reputation: 664

Memory allocation and releasing memory

I'm a newbie using V++ and I've been wondering about some memory behavior.
I wrote similar classes to what is causing me problems. The questions are written in the comments of the code.

class A
{
private:
    int _number;
public:
    A(int number) : _number(number)
    {}

    const int& getNumber() const
    {
        return _number;
    }

    void setNumber(const int& number)
    {
        _number = number;
    }
}

class B
{
private:
    A _a;
    bool _hasA;

public:
    B() : _hasA(false)
    {}

    B(const A & a) : _a(a), _hasA(true)
    {}

    void setA(const A & a)
    {
        _a = a;
    }

    const A& getA() const
    {
        return _a;
    }

    const bool hasA() const
    {
        return _hasA;
    }

    void removeA()
    {
        // ??
    }
}

int main()
{
    A a(5);

    B b1; // Is the A space allocated even if no value is affected to it ?
    B b2(a);

    b1.setA(b2.getA()); // I actually want to move "a" from b2 to b1 without leaving it in b2
    b1.removeA(); // Do I need to write a removeA() function and how would it be?
}

b1.setA(b2.getA()); copies A into b1 too instead of moving it.

Thanks for your help.

EDIT: To answer those who are confused like I just was:

Me : I just understood that when instanciating b1 it needed the A::A() constructor. I thought it'd be like "null" or something if I created b1 without instantiating _a.

Zac Howland: @SanjamX I see your confusion now. In managed languages, (most) everything is a pointer, so if you do not instantiate it (e.g. A a instead of A a = new A()), it is just a null pointer. In C/C++, if you declare something as A a, you instantiated it "on the stack". It is an automatic variable that will be deallocated when it goes out of scope. You are still instantiating it, however. This question may help you understand better.

Upvotes: 0

Views: 106

Answers (1)

Zac Howland
Zac Howland

Reputation: 15870

B b1();

That does not do what you think it does. It is declaring a function b1 that takes no parameters and returns a B.

b1.setA(b2.getA());
b1.removeA();

Because of the previous situation, the 2 lines above will give you a compiler error.

The "move" you are asking about will actually be a copy (in this case). You can use the C++11 move semantics to do an actual move, but it is entirely unnecessary with the current code. Alternatively, you can change your class to do a move using pointers (which could potentially be useful) - which would use std::unique_ptr<A> _a, instead of A _a.

Upvotes: 3

Related Questions