Copy Constructor and memory allocation

M

Michael

Hi,
I'm writing a vector class:

//mv3.h

class mv3Impl;

class mv3
{
public:
mv3();
mv3(mv3&);
mv3& operator= ( const mv3& RHS);

private:
mv3Impl* pImpl;
};



//mv3.cpp

class mv3Impl
{
public:
float x,y,z;
};

mv3::mv3()
{
pImpl = new mv3Impl;
pImpl->x = pImpl->y = pImpl->z = 1.0f;
}

mv3::mv3(mv3& v)
{
pImpl = new mv3Impl;
*pImpl = *(v->pImpl);
}

mv3& mv3::eek:perator= ( const mv3& RHS)
{
pImpl = new mv3Impl; /* <----------------Do I need this line??
*/
*pImpl = *(RHS->pImpl);

}

Do i need the line that allocates memory or will this create a memory leak?
What functions are called in:

mv3 a;
mv3 b = a;

??
Thanks

Mike
 
J

John Harrison

Michael said:
Hi,
I'm writing a vector class:

//mv3.h

class mv3Impl;

class mv3
{
public:
mv3();
mv3(mv3&);

Should be

mv3(const mv3&);
mv3& operator= ( const mv3& RHS);

private:
mv3Impl* pImpl;
};



//mv3.cpp

class mv3Impl
{
public:
float x,y,z;
};

mv3::mv3()
{
pImpl = new mv3Impl;
pImpl->x = pImpl->y = pImpl->z = 1.0f;
}

mv3::mv3(mv3& v)
{
pImpl = new mv3Impl;
*pImpl = *(v->pImpl);
}

mv3& mv3::eek:perator= ( const mv3& RHS)
{
pImpl = new mv3Impl; /* <----------------Do I need this line??
*/

No. You are assigning to an already existing object, so it will already have
allocated some memory.
*pImpl = *(RHS->pImpl);

}

Do i need the line that allocates memory or will this create a memory
leak?

A memory leak.
What functions are called in:

mv3 a;
mv3 b = a;

First line - default constructor
Second line - copy constructor

John
 
J

Jeff Flinn

Michael said:
Hi,
I'm writing a vector class:

//mv3.h

class mv3Impl;

class mv3
{
public:
mv3();
mv3(mv3&);
mv3& operator= ( const mv3& RHS);

private:
mv3Impl* pImpl;
};



//mv3.cpp

class mv3Impl
{
public:
float x,y,z;
};

mv3::mv3()
{
pImpl = new mv3Impl;
pImpl->x = pImpl->y = pImpl->z = 1.0f;
}

mv3::mv3(mv3& v)
{
pImpl = new mv3Impl;
*pImpl = *(v->pImpl);
}

mv3& mv3::eek:perator= ( const mv3& RHS)
{
pImpl = new mv3Impl; /* <----------------Do I need this line??
*/
*pImpl = *(RHS->pImpl);

}

Do i need the line that allocates memory or will this create a memory
leak?

Yes, In addition to the already existing memory leak(s). Think about it.

Jeff F
 
J

John Harrison

Michael said:
Sorry But I can't see the relevance, please explain further.
Fanks
Mike

More or less any post that is about vectors and the like, Robert advertises
his vector library.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top