How to properly pass unique_ptr to a constructor or function?
Hi! I recently started learning C++11 and am trying to understand smart pointers, specifically std::unique_ptr. I read that they help manage memory automatically and don't require delete. But I have a problem: I don't understand how to properly pass unique_ptr to functions and constructors.
Here's a simple class I wrote:
```cpp
#include
#include
class MyClass {
public:
MyClass(std::unique_ptr ptr) : data(std::move(ptr)) {
std::cout << "Created with value: " << *data << std::endl;
}
private:
std::unique_ptr data;
};
void processData(std::unique_ptr ptr) {
std::cout << "Processing: " << *ptr << std::endl;
}
int main() {
auto p = std::make_unique(42);
// How to pass p to the constructor
No answers yet.
Log in to leave an answer
Blogs