Why can you return std::unique_ptr from a function without std::move?
Hello! I recently started learning C++11 and smart pointers, and I got confused with std::unique_ptr. I know that unique_ptr cannot be copied — only moved. To move, std::move() is usually used. But I noticed strange behavior: when I write a function that creates and returns a unique_ptr, the compiler doesn't complain even if I don't call std::move().
Here's an example:
```cpp
#include
std::unique_ptr createInt() {
std::unique_ptr ptr = std::make_unique(42);
return ptr; // Without std::move() — and it works!
}
int main() {
std::unique_ptr p = createInt();
return 0;
}
```
Why does this compile? After all, unique_ptr prohibits copying! If I try to do the same with a regular variable in another function, for example
No answers yet.
Log in to leave an answer