DEV Community

Discussion on: What's unique pointer in C++

 
gapry profile image
Gapry • Edited

Hi, Dave Cridland

Agree!! You're right !!!! I'm wrong, sorry.

If I change the code as following, what do you think?

auto task(point* pt_) -> void {
  auto pt = beta::unique_ptr<point<float>>(pt_);
  // skip the left detail implementation.
}
auto pt = new point<float>(1.2f, 2.3f, 3.4f, 4.5f);
auto worker1 = std::thread(task, pt);
auto worker2 = std::thread(task, pt);
auto worker3 = std::thread(task, pt);
// skip the left detail implementation.

Thank you for your rely.

Best regards, Gapry.

Thread Thread
 
dwd profile image
Dave Cridland

Right! If you do that, you will get a double-free, and essentially nothing can protect you (because the m_ptr of each unique_ptr is independent). But also, you don't need to use threads to do it - and it's why best practise with smart pointers is to use std::make_unique:

auto pt = std::make_unique<point<float>>(1.2f, 2.3f, 3.4f, 4.5f);
Thread Thread
 
gapry profile image
Gapry

Hi, Dave Cridland

Thank you for your rely, insights and suggestion!

Best regards, Gapry.