Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

I want to pass an object by reference into a function (of another class), can this be done without causing a memory leak or requiring me to perform a delete?

 

Allow me to illustrate what I mean ...


class A
{
vector<B*> v; // vector of pointers to Class B objects

void Add(B &b) // function to add pointers to vector
{
v.push_back(b);
}
~A {... delete everything from the vector ...}
};

class B
{
... some stuff ...
};

void main()
{
A *a; // pointer to instance of A
a = new A();
a->Add(new B());
}
[/COde]

 

So, the question is for the following line in particular:

a->Add(new B());

In this case I create a new Instance of B() which is passed (by reference) to the A.Add() function ... Can I do this or will it cause a memory leak? Also will the vector in A() have a correct pointer to the object created and passed in?

 

My goal is to simply pass the instance to Class A without making the vector public and accessing it directly...

 

Let me know if that makes any sense...

Thanks,

Edited by Shaitan00
Posted

If I make the following code-changes it compiles and seems to work ... but is there a memory leak due to my "NEW" inside of MAIN?

 


void Add(B *b) // function to add pointers to vector
[/Code]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...