0

I have code like this...

X* raw = ::new X("abc");
// do something benign to object
std::shared_ptr<X> ptr(raw);

Now consider the same using an object factory...

template<typename T, typename... A>
std::shared_ptr<T> factory(A&&... args) {
    auto ptr = std::make_shared<T>(std::forward<A>(args)...);
    // do something benign to object
    return ptr;
}

std::shared_ptr<X> ptr = factory<X>("abc");    

This is a simplified example, but I'm seeing an unexplained crash when using the factory that appears to be due to a corrupted shared pointer.

I'm not familiar with the innards of std::make_shared, but am wondering if it in turn does something like argument forwarding to placement ::new, and that this chain forwarding is a problem.

jotik
  • 17,044
  • 13
  • 58
  • 123
user1715587
  • 155
  • 1
  • 10
  • Your code looks OK to me, including the forwarding. Can you provide a stack trace of the crash? You might want to try to run it with [valgrind](http://valgrind.org/). – jotik Jul 31 '17 at 13:55
  • 1
    Could you provide a [mcve]? – cpplearner Jul 31 '17 at 13:57
  • When you `make_shared`, the object and the reference counting and the like are located right next to each other. When you allocate then wrap a shared ptr around it, they exist far away. If you are corrpting memory right before your object, in the `make_shared` case you'll be corrupting the shared ptr booking data... – Yakk - Adam Nevraumont Jul 31 '17 at 18:41
  • Retracting the question. Something in the "benign" process was actually not. – user1715587 Aug 01 '17 at 02:29

0 Answers0