shared_ptr with no-op deleter
{ edited by mod to shorten lines to ~70 chars. -mod }
Hi,
I stumbled upon a problem that I first thought could be a compiler
problem, but since this seems to be happening in both MSVC 2013 and
g++ 4.9.2 I think that maybe my understanding of the standard is not
correct.
Is code below legal?
(For unforgivable reasons, but...) I am creating shared pointers to
a statically-allocated object with a no-op custom deleter. While this
used to work with boost::shared_ptr without a problem, it seems to crash
with std::shared_ptr in the scenario when multiple threads are creating
the shared pointers concurrently. I think I've heard that there is
a subtle difference between std::shared_ptr and boost::shared_ptr
implementation related to the counters allocation, and the crashes I'm
experiencing do seem to appear when a shared pointer gets destroyed (and
the counter reaches zero and - I assume - tries to destroy the counter,
but it looks as if the memory has already been free'd - at least this is
what Valgrind is telling me).
I was unable to create a small repro though; the code below does seem to
work. In my real scenario, the 'getpint' function resides in
a dynamically linked library (but I don't know whether that could be
a contributing factor).
Thanks,
Filip
#include <memory>
typedef std::shared_ptr<int> pint;
pint getpint() {
static int i = 0;
return std::shared_ptr<int>(&i, [](int*){ /* nop */ });
}
int main(int argc, char* argv[]) {
std::thread t1([]() {
for(int x = 0; x<10000000; ++x) {
getpint();
}
});
std::thread t2([]() {
for(int x = 0; x<10000000; ++x) {
getpint();
}
});
t1.join();
t2.join();
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]