Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #15215
| From | Alex <acamposr@gmail.com> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Using swap idiom for exception safety in a constructor |
| Date | 2012-04-03 17:52 -0700 |
| Organization | http://groups.google.com |
| Message-ID | <16873120.1684.1333500772985.JavaMail.geo-discussion-forums@pbgr6> (permalink) |
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
Back to comp.lang.c++ | Previous | Next — 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