Re: Guarantee of side-effect free assignment
* Jiri Palecek:
I think one of the problems with your solution with a randomly throwing
Non-provably not-throwing, not randomly throwing. ;-)
constructor could be a compiler can still rewrite it like this:
Singleton* Singleton::instance()
{
if (pInstance == 0)
{
Lock lock;
if (pInstance == 0)
{
// we know pInstance is 0 here
pInstance = // Step 3
operator new(sizeof(Singleton)); // Step 1
try {
new (pInstance) Singleton; // Step 2
} catch(...) {
delete (void*)pInstance;
pInstance=0;
throw;
}
}
}
return pInstance;
}
And this transformation is legal (at least I think) as long as
Singleton::Singleton() (even in case of an exception) doesn't call
Singleton::instance() (and the allocation and deallocation function
likewise). You could only see the pointer to the non-constructed from an
async signal (but that's OK, because even the pointer is not sig_atomic_t,
so can be anything in an async signal) or from a different thread, but the
standard doesn't say anything about threads.
If pInstance is a non-local static it can be inspected from within the
Singleton constructor. The rewrite will then have changed the effect of
a normal single-threaded program. So at least in that case, it's not
allowed (assuming Greg's logic holds, which I think it does).
Which means that the conclusion that the assignment has to happen after
the constructor, is incompatible with the Meyers/Alexandrescu conclusion
that "there is no way to express this constraint in C or C++".
Cheers,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]