| RAII [message #17263] |
Fri, 05 October 2007 10:51  |
Naren Messages: 2 Registered: October 2007 |
Junior Member |
|
|
Please tell me which of this is correct.
class B
{
A a;
public:
B(){a.Doif();}
~B(){a.Doelse();}
};
class B
{
A* a;
public:
B():a(new A) {a->Doif();}
~B(){a->Doelse();delete a;}
};
Second one will always work.
Is first one undefined, though I have verified that both works correctly.
Application created using Microsoft compiler.
Thanks in advance.
Thanks,
Naren.
|
|
|
|
|
|
| Re: RAII [message #17269 is a reply to message #17266 ] |
Fri, 05 October 2007 13:21   |
Daniel Kraft Messages: 21 Registered: August 2007 |
Junior Member |
|
|
Naren wrote:
> "Erik Wikström" <Erik-wikstrom@telia.com> wrote in message
> news:jjsNi.10477$ZA.7039@newsb.telia.net...
>> On 2007-10-05 16:51, Naren wrote:
>>> Please tell me which of this is correct.
>>>
>>> class B
>>> {
>>> A a;
>>> public:
>>> B(){a.Doif();}
>>> ~B(){a.Doelse();}
>>> };
>>>
>>> class B
>>> {
>>> A* a;
>>> public:
>>> B():a(new A) {a->Doif();}
>>> ~B(){a->Doelse();delete a;}
>>> };
>>>
>>> Second one will always work.
>>>
>>> Is first one undefined, though I have verified that both works correctly.
>> In what way? I would probably use the first one, but it depends on what
>> A and B are and how I would use them.
>
> Since I am in the destructor, any issues?
No, as in the second version, a is destructed after the destructor of B
is finished, so in it you can work with a to your liking.
Cheers,
Daniel
--
Got two Dear-Daniel-Instant Messages
by MSN, associate ICQ with stress--so
please use good, old E-MAIL!
|
|
|
|
|
| Re: RAII [message #17390 is a reply to message #17289 ] |
Sun, 07 October 2007 07:55  |
Rolf Magnus Messages: 27 Registered: August 2007 |
Junior Member |
|
|
R Samuel Klatchko wrote:
> Dynamic allocation is more complex to handle because it gives you the
> ability to detect low memory conditions. When the heap is full (or too
> fragmented) to fulfill your request, new will throw and you will
> probably want to handle that situation.
Depends. A typical desktop system will become unresponsive long before that.
|
|
|