DEV Community

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

 
dwd profile image
Dave Cridland

No, because the point instances are unique in each thread.

If you put the following into the task lambda, you'll see:

  // ...
  std::cout << &pt << ' ' << &*pt << std::endl;
  // ...

That will show different pointer values for all three unique pointers, and the objects they point to.

You literally cannot (implicitly) call a destructor more than once without some really esoteric and low-level behaviour (such as using the clone() system call on Linux to fork into a thread).

Thread Thread
 
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.