Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #15219
| From | goran.pusic@gmail.com |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: Using swap idiom for exception safety in a constructor |
| Date | 2012-04-04 05:07 -0700 |
| Organization | http://groups.google.com |
| Message-ID | <21443010.167.1333541256069.JavaMail.geo-discussion-forums@yncc6> (permalink) |
| References | <16873120.1684.1333500772985.JavaMail.geo-discussion-forums@pbgr6> |
On Wednesday, April 4, 2012 2:52:52 AM UTC+2, Alex wrote:
> Hi, I want to ensure exception safety inside a constructor by creating a temporary object and then swapping it with *this:
>
> class Test {
> public:
> Test(int value) : p(0)
> {
> Test tmp;
> tmp.initialize(value); // In case of exception, tmp is destroyed
> swap(tmp);
> }
>
> ~Test()
> {
> if (p) delete p;
> };
>
> swap(Test& other) {...}
>
> private:
> Test() : p(0) {}
>
> void initialize(int value)
> {
> p = new X(value, ...);
> // and more members...
> }
>
> private:
> X * p;
> // And many more members...
> };
>
> I wanted to know:
> a) Is this a common approach?
> b) What other options do you recommend when this is not possible (e.g. Test has pure-virtual methods so I can't instantiate the tmp object)?
>
> Thanks
(If I understand you correctly... I presume you have e.g. Y* p2, Z* p3 etc. as a member of Test)
This is not good, and I would hazard it's not common either. It's bad because you just moved the leak from "this" to tmp.Initialize: e.g. if "new p2" fails, p1 is leaked.
One correct approach is e.g.:
class Test
{
X* p1; Y* p2;
public:
Test(A a, B b) : p1(0), p2(0)
{
// can-throw zone here
auto_ptr<X> P1(new X(a)); // unique_ptr in C++11?
auto_ptr<Y> P2(new X(b));
// no-throw zone here
p1 = P1.release();
p2 = P2.release();
}
~Test()
{ // look, ma, no if-s!
delete p1; delete p2;
}
};
In short, use of auto_ptr in the constructor ensures proper cleanup.
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Using swap idiom for exception safety in a constructor Alex <acamposr@gmail.com> - 2012-04-03 17:52 -0700 Re: Using swap idiom for exception safety in a constructor Howard Hinnant <howard.hinnant@gmail.com> - 2012-04-03 19:52 -0700 Re: Using swap idiom for exception safety in a constructor goran.pusic@gmail.com - 2012-04-04 05:07 -0700 Re: Using swap idiom for exception safety in a constructor "Alf P. Steinbach" <alf.p.steinbach+usenet@gmail.com> - 2012-04-04 23:19 +0200
csiph-web