0

I got a piece of code which uses a std::set to keep a bunch of pointer.

I used this to be sure of that each pointer will present only once in my container.

Then, I heard about std::unique_ptr that ensure the pointer will exists only once in my entire code, and that's exactly what I need.

So my question is quite simple, should I change my container type to std::vector ? Or It won't changes anything leaving a std::set ?

7
  • std::unique_ptr doesn't ensure that only one pointer points to a certain address. Commented Apr 19, 2018 at 13:47
  • Yes, but if I create my object with new std::unique_ptr< ... >(new ...()), or std::make_unique< ... >( ... ) ? Commented Apr 19, 2018 at 13:49
  • Should the container own the objects pointed to by the pointers? Do you even need pointers in the first place? Commented Apr 19, 2018 at 13:54
  • 1
    You are pretty safe when using make_unique. But you won't get total safety at any point. I.e. auto x = new xyz(); auto a = unique_ptr(x), b = unique_ptr(x); and don't use new to create a unique_ptr, you will lose the advantages smart pointers give you. Commented Apr 19, 2018 at 13:57
  • Timo, I'm ok with new xyz() example. Commented Apr 19, 2018 at 14:02

1 Answer 1

1

I think the job your set is doing is probably different to unique_ptr.

Your set is likely recording some events, and ensuring that only 1 event is recorded for each object that triggers, using these terms very loosely.
An example might be tracing through a mesh and recording all the nodes that are passed through.
The objects themselves already exist and are owned elsewhere.

The purpose of unique_ptr is to ensure that there is only one owner for a dynamically allocated object, and ensure automatic destruction of the object. Your objects already have owners, they don't need new ones!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.