2

Isn't std::unique_ptr designed to be an unique pointer to a memory, and no other pointer should point to this memory ?

Then why does std:unique_ptr has a get() member function which returns a raw pointer to the memory owned by the std::unique_ptr ?

So by using get() we can create numerous owners ( raw pointers ) to the std::unique_ptr's memory, isn't that senseless ?

user2591935
  • 299
  • 1
  • 14
  • not raw pointers are owners. It's only an owner if you say it is. – Mooing Duck Oct 30 '14 at 22:41
  • They have total control of the memory which they point, why they wouldn't be considered as owners ? – user2591935 Oct 30 '14 at 22:42
  • As long as you have placed the pointer to your allocated memory into a `std::unique_ptr` (at the correct scope) you can safely use the raw pointer (obtained with `get()`) throughout that scope knowing it will be deleted at the appropriate time. – Galik Oct 30 '14 at 22:45
  • @Galik Can't someone do `delete ptr.get()` before it goes out of scope? – David G Oct 30 '14 at 22:50
  • @0x499602D2 Someone COULD do that. C++ allows people doing stuff they shouldn't do in many ways, so why should that particular stupidity be "not possible". As explained in my answer, there are things that you simply can't do without a `get` function. – Mats Petersson Oct 30 '14 at 22:52
  • @0x499602D2 Of course. But why would anyone do that? – Galik Oct 30 '14 at 23:00
  • These days IMHO the vast majority of the time C++ programmers should not be thinking in terms of deleting raw pointers. They should be thinking about where to place the creation of the smart pointer and which smart pointer is appropriate for the task in hand. Then you can enjoy the speed of the raw pointer safely knowing its lifetime is managed. – Galik Oct 30 '14 at 23:07
  • @user2591935: If a guy holds a gun to my head, he has pretty much total control over me at that point. Doesn't mean he owns me or my stuff though. Control does not imply ownership. – Mooing Duck Oct 30 '14 at 23:11

1 Answers1

4

Imagine that you do:

void process_file()
{
   const int max_size = 10000; 
   std::unique_ptr<char[]> buffer(new char[max_size]); 

   ifstream f("myfile.txt"); 

   f.read(buffer.get(), max_size); 
   ... 
   ... process buffer
   ...
}

How would you do this without get()? unique_ptr can't be passed to istream::read as it is.

Well, as the comment says, you can do it by using &*buffer, but that is far from easy to follow - using buffer.get() clearly states to the reader that "this is the raw pointer inside the buffer.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 1
    "How would you do this without get()?" `&*buffer` – D Drmmr Oct 30 '14 at 22:54
  • 1
    Exactly. The better answer is that having `get` allows you to make it clear that you're extracting a naked pointer from a unique pointer, rather than requiring people to figure it out from `&*` or from comments. – David Schwartz Oct 30 '14 at 22:56