Chen Wei
Chen Wei

Reputation: 402

How to pass the reference of unique_ptr.get() to a function

I have the following code, however it reports error: invalid initialization of non-const reference of type 'char*&' from an rvalue of type 'std::unique_ptr<char []>::pointer {aka char*}'. I am wondering if I can buffer allocation in a function for a unique_ptr in this way.

#include <iostream>
#include <string>
#include <memory>

void buffer_test(char* &buffer){

    buffer = new char[100];
}

int main()
{



    std::unique_ptr<char []> buffer{};

    buffer_test(buffer.get());

    std::cout << buffer[0] << std::endl;

    std::cout << "finish";
}

Upvotes: 0

Views: 1890

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474326

unique_ptr::get does not return a reference to the pointer object within the unique_ptr object. It returns the pointer value. You get a copy of it, not a reference.

So you cannot pass that value to a function with takes a non-const reference to a pointer. If you want to fill in the unique_ptr's actual stored pointer value, you will *have to * pass the unique_ptr itself to buffer_test, or just have buffer_test return the pointer it allocates.

Or even better, have it return a unique_ptr to the buffer it allocates. Because there's basically no reason not to.

Upvotes: 4

Related Questions