473,424 Members | 1,695 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,424 software developers and data experts.

question on initializing a pointer to an object and releasing the memory.

Hi All,

I have encapsulate CvMat of OpenCV into my own matrix class as the
following:

class CVMatrix
{
//== Fields
private:
unsigned m_Width;
unsigned m_Height;
CvMat* m_Matrix;

//== Constructors and destructor
public:
CVMatrix(); // empty constructor
CVMatrix(int width, int height); // formal constructor
CVMatrix(const CVMatrix& matrix); // copy constructor
~CVMatrix();
}; // CVMatrix

Constructor is defined as (e.g. CVMatrix(int width, int height)
CVMatrix::CVMatrix(int width, int height)
{
if (width <= 0 || height <= 0)
exit(0);
m_Width = width;
m_Height = height;
m_Matrix = cvCreateMat(m_Height, m_Width, FLOAT);
}

Destructor is defined as:
CVMatrix::~CVMatrix()
{
cvReleaseMat(&m_Matrix);
}

If I use the matrix as initializing an instance:

CVMatrix a(4, 4);

matrix a can be released at the end of program.

However, if the matrix is initialized as a pointer:

CVMatrix* a = new CVMatrix(4, 4);

The destructor would never been called, and causes memory leak problem.
Moreover, when the matrix array is required, such as

CVMatrix** matrixArray = new CVMatrix*[length];
for (int i = 0; i < length; i ++)
matrixArray[i] = new CVMatrix(4, 4);

There would be severe memory leak problem since the destructor would
never been called for all those CVMatrix(s).

Would be appreciated should any body teach me the formal way using the
object pointer, as well as the object array, whist the destructor can
be correctly called.

Aug 21 '06 #1
11 2263
sg*********@gmail.com wrote:
Hi All,

I have encapsulate CvMat of OpenCV into my own matrix class as the
following:

class CVMatrix
{
//== Fields
private:
unsigned m_Width;
unsigned m_Height;
CvMat* m_Matrix;

//== Constructors and destructor
public:
CVMatrix(); // empty constructor
CVMatrix(int width, int height); // formal constructor
CVMatrix(const CVMatrix& matrix); // copy constructor
~CVMatrix();
You probably also need an assignment operator.
}; // CVMatrix

Constructor is defined as (e.g. CVMatrix(int width, int height)
CVMatrix::CVMatrix(int width, int height)
{
if (width <= 0 || height <= 0)
exit(0);
m_Width = width;
m_Height = height;
m_Matrix = cvCreateMat(m_Height, m_Width, FLOAT);
}

Destructor is defined as:
CVMatrix::~CVMatrix()
{
cvReleaseMat(&m_Matrix);
}

If I use the matrix as initializing an instance:

CVMatrix a(4, 4);

matrix a can be released at the end of program.

However, if the matrix is initialized as a pointer:

CVMatrix* a = new CVMatrix(4, 4);

The destructor would never been called, and causes memory leak problem.
The destructor is called as soon as you delete your matrix. And you should
always delete the objects you get from new.
Moreover, when the matrix array is required, such as

CVMatrix** matrixArray = new CVMatrix*[length];
for (int i = 0; i < length; i ++)
matrixArray[i] = new CVMatrix(4, 4);

There would be severe memory leak problem since the destructor would
never been called for all those CVMatrix(s).

Would be appreciated should any body teach me the formal way using the
object pointer,
delete a;
as well as the object array,
for (int i = 0; i < length; ++i)
delete matrixArray[i];
delete [] matrixArray;
whist the destructor can be correctly called.

Aug 21 '06 #2
sg*********@gmail.com wrote:
Hi All,

I have encapsulate CvMat of OpenCV into my own matrix class as the
following:

class CVMatrix
{
//== Fields
private:
unsigned m_Width;
unsigned m_Height;
CvMat* m_Matrix;

//== Constructors and destructor
public:
CVMatrix(); // empty constructor
CVMatrix(int width, int height); // formal constructor
CVMatrix(const CVMatrix& matrix); // copy constructor
~CVMatrix();
}; // CVMatrix

Constructor is defined as (e.g. CVMatrix(int width, int height)
CVMatrix::CVMatrix(int width, int height)
{
if (width <= 0 || height <= 0)
exit(0);
m_Width = width;
m_Height = height;
m_Matrix = cvCreateMat(m_Height, m_Width, FLOAT);
}

Destructor is defined as:
CVMatrix::~CVMatrix()
{
cvReleaseMat(&m_Matrix);
}

If I use the matrix as initializing an instance:

CVMatrix a(4, 4);

matrix a can be released at the end of program.

However, if the matrix is initialized as a pointer:

CVMatrix* a = new CVMatrix(4, 4);

The destructor would never been called, and causes memory leak problem.
The destructor will be called when you say

delete a;

which you should do for any pointer that you new.
Moreover, when the matrix array is required, such as

CVMatrix** matrixArray = new CVMatrix*[length];
for (int i = 0; i < length; i ++)
matrixArray[i] = new CVMatrix(4, 4);

There would be severe memory leak problem since the destructor would
never been called for all those CVMatrix(s).
Here you need to says

delete matrixArray[i];

for each index i, and then, you should do:

delete[] matrixArray;

because this is how get rid of arrays that you new[]ed.

Would be appreciated should any body teach me the formal way using the
object pointer, as well as the object array, whist the destructor can
be correctly called.
The best way of dealing with pointers is not to. You may want to consider
using tr1::shared_ptr<CVmatrixinstead which will call the destructor of
the pointee and release the allocated memory as soon as the last pointer to
the pointee goes out of scope. (At least that is what it does as long as
you do not create cyclic data structures.)

Pointers are about the most tricky aspect of C++: every new has to be
matched with a delete along each path of execution. Since exceptions can
divert the path of execution on almost any given line, this gets out of
control rather quickly. Therefore, it is best practice to use new only in
constructors and place the corresponding delete within the destructor. This
way proper matching is guaranteed by the language. If you feel the need for
a pointer in your program, very likely you want to use a smart pointer
instead.
Best

Kai-Uwe Bux

Aug 21 '06 #3
Many thx to the above!
Kai-Uwe Bux wrote:
sg*********@gmail.com wrote:
Hi All,

I have encapsulate CvMat of OpenCV into my own matrix class as the
following:

class CVMatrix
{
//== Fields
private:
unsigned m_Width;
unsigned m_Height;
CvMat* m_Matrix;

//== Constructors and destructor
public:
CVMatrix(); // empty constructor
CVMatrix(int width, int height); // formal constructor
CVMatrix(const CVMatrix& matrix); // copy constructor
~CVMatrix();
}; // CVMatrix

Constructor is defined as (e.g. CVMatrix(int width, int height)
CVMatrix::CVMatrix(int width, int height)
{
if (width <= 0 || height <= 0)
exit(0);
m_Width = width;
m_Height = height;
m_Matrix = cvCreateMat(m_Height, m_Width, FLOAT);
}

Destructor is defined as:
CVMatrix::~CVMatrix()
{
cvReleaseMat(&m_Matrix);
}

If I use the matrix as initializing an instance:

CVMatrix a(4, 4);

matrix a can be released at the end of program.

However, if the matrix is initialized as a pointer:

CVMatrix* a = new CVMatrix(4, 4);

The destructor would never been called, and causes memory leak problem.

The destructor will be called when you say

delete a;

which you should do for any pointer that you new.
Moreover, when the matrix array is required, such as

CVMatrix** matrixArray = new CVMatrix*[length];
for (int i = 0; i < length; i ++)
matrixArray[i] = new CVMatrix(4, 4);

There would be severe memory leak problem since the destructor would
never been called for all those CVMatrix(s).

Here you need to says

delete matrixArray[i];

for each index i, and then, you should do:

delete[] matrixArray;

because this is how get rid of arrays that you new[]ed.

Would be appreciated should any body teach me the formal way using the
object pointer, as well as the object array, whist the destructor can
be correctly called.

The best way of dealing with pointers is not to. You may want to consider
using tr1::shared_ptr<CVmatrixinstead which will call the destructor of
the pointee and release the allocated memory as soon as the last pointer to
the pointee goes out of scope. (At least that is what it does as long as
you do not create cyclic data structures.)

Pointers are about the most tricky aspect of C++: every new has to be
matched with a delete along each path of execution. Since exceptions can
divert the path of execution on almost any given line, this gets out of
control rather quickly. Therefore, it is best practice to use new only in
constructors and place the corresponding delete within the destructor. This
way proper matching is guaranteed by the language. If you feel the need for
a pointer in your program, very likely you want to use a smart pointer
instead.
Best

Kai-Uwe Bux
Aug 21 '06 #4
sg*********@gmail.com wrote:
Many thx to the above!
Kai-Uwe Bux wrote:
>sg*********@gmail.com wrote:
[...]

Please don't top-post.

Please don't post just to say "thanks"

Please don't quote the entire message when you don't refer to any of it.

What or who is "the above" you're referring to? Your statement is the
very first line in your message.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 21 '06 #5

Also, if you write your own copy constructor for a class, it's good
practice to also provide an
assignment operator.

Tolga Ceylan

Aug 21 '06 #6
Victor Bazarov wrote:
Please don't post just to say "thanks"
Well, if the OP doesn't answer at all, it always feels like he ignored the
replies to his posting. I think it's a good idea to say "thanks".

Aug 21 '06 #7
Rolf Magnus wrote:
Victor Bazarov wrote:
>Please don't post just to say "thanks"

Well, if the OP doesn't answer at all, it always feels like he
ignored the replies to his posting. I think it's a good idea to say
"thanks".
I think it's a waste of bandwidth and my time. I see another post by
the OP, and open it, thinking it might be another question on the same
subject, or an explanation, or the final review of the proposed fix...
And what do I find? A top-posted thank-you note with the rest of it
hanging below! Annoying. Thank in advance and be done with it. If
one needs a confirmation of whether the OP read the replies, send them
a private e-mail on that. I couldn't care less if they read it or not,
in all honesty.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 21 '06 #8
Victor Bazarov wrote:
Rolf Magnus wrote:
Victor Bazarov wrote:
Please don't post just to say "thanks"
Well, if the OP doesn't answer at all, it always feels like he
ignored the replies to his posting. I think it's a good idea to say
"thanks".

I think it's a waste of bandwidth and my time. I see another post by
the OP, and open it, thinking it might be another question on the same
subject, or an explanation, or the final review of the proposed fix...
And what do I find? A top-posted thank-you note with the rest of it
hanging below! Annoying. Thank in advance and be done with it. If
one needs a confirmation of whether the OP read the replies, send them
a private e-mail on that. I couldn't care less if they read it or
not, in all honesty.
I disagree with your main point. "Thank you" messages don't bother me
in the slightest, and I often acknowledge responses that I get to
questions.

Your point about top-posting is well taken, of course, but that would
apply to any response.


Brian
Aug 21 '06 #9
"Default User" <de***********@yahoo.comwrote...
[..] "Thank you" messages don't bother me
in the slightest, and I often acknowledge responses that I get to
questions.
Thank you notes add nothing technical to the discussion. They are
unnecessary if the original post has a "thank you in advance". Any
acknowledgement can come in a brief technical summary of the previous
points and definitely doesn't need to include the entire previous post.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 21 '06 #10
Victor Bazarov wrote:
"Default User" <de***********@yahoo.comwrote...
[..] "Thank you" messages don't bother me
in the slightest, and I often acknowledge responses that I get to
questions.

Thank you notes add nothing technical to the discussion.
Lots of what gets posted adds no technical details. Like, for instance,
complaining about thanks. Or complaining about complaining about thanks.
They are
unnecessary if the original post has a "thank you in advance". Any
acknowledgement can come in a brief technical summary of the previous
points and definitely doesn't need to include the entire previous
post.
That's your opinion. It's not mine. Acknowledgement from the recipient
lets the contributors know that the specific advice given was useful.
That can't be done with a TIA.


Brian
Aug 21 '06 #11

"Default User" <de***********@yahoo.comwrote in message
news:4k************@individual.net...
Victor Bazarov wrote:
>"Default User" <de***********@yahoo.comwrote...
[..] "Thank you" messages don't bother me
in the slightest, and I often acknowledge responses that I get to
questions.

Thank you notes add nothing technical to the discussion.

Lots of what gets posted adds no technical details. Like, for instance,
complaining about thanks. Or complaining about complaining about thanks.
>They are
unnecessary if the original post has a "thank you in advance". Any
acknowledgement can come in a brief technical summary of the previous
points and definitely doesn't need to include the entire previous
post.

That's your opinion. It's not mine. Acknowledgement from the recipient
lets the contributors know that the specific advice given was useful.
That can't be done with a TIA.
Just to continue this OT fun...

The TIA concept reminds me of something I learned in my youth, which you
might have heard before:

"For all [the help] that I am about to receive, may I be truly thankful."
:-)

-H

Aug 21 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in...
20
by: __PPS__ | last post by:
Hello everybody in a quiz I had a question about dangling pointer: "What a dangling pointer is and the danger of using it" My answer was: "dangling pointer is a pointer that points to some...
4
by: xyu | last post by:
Hello, First I would like to thank anyone who helps me, much appreciated. I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off...
5
by: pitdog | last post by:
Hello, I am unable to find information on about this issue so I thought I would post and ask. I have a class that is using the sigleton pattern as it has an internal static instance of...
21
by: Roland | last post by:
The following issue is puzzling me: There are 2 ways of writing the code below: .... Dim fnt as Font = New Font(...) DrawString(myText, fnt,...) fnt.dispose(). or DrawString(myText, New...
13
by: Aarti | last post by:
I have a very elementary question about pointers. Please pardon me for my ignorance of C int main() { int* i; *i = 1 //at times this may give me a core dump. const char* str = "test"; //This...
4
by: ajk | last post by:
Hi Given an array of bytes i.e. cli::array<Byte>^ar I would like convert from and to a structure/class What is the best way to do this in C++/CLI ? I have looked at using a union class A
18
by: subramanian100in | last post by:
Consider a class that has vector< pair<int, string>* c; as member data object. I need to use operator>to store values into this container object and operator<< to print the contents of the...
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.