1

I have a function like this:

unique_ptr<int> foo() {
    return unique_ptr<int>(new int[4])
}

When calling this foo(), what I do is:

unique_ptr<int> t = foo()

I am wondering is there any problem in this piece of code? Should I use something like std::move instead of assigning directly? Can I return the unique ptr by reference, like:

unique_ptr<int>& foo() {
    return unique_ptr<int>(new int[4])
}
WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30
  • 1
    What does the `[...]` in `unique_ptr(new int[...])` represent? You're not allocating an array there are you? Because if you are, you have undefined behavior when that `unique_ptr` is destroyed. – Benjamin Lindley May 23 '13 at 00:57
  • @BenjaminLindley, Good point. I assumed it was allocating a single element. – chris May 23 '13 at 00:58
  • why? unique_ptr will destroy the array, right? – WhatABeautifulWorld May 23 '13 at 01:01
  • @WhatABeautifulWorld, It defaults to `delete ptr;`. You need to use an empty array type argument to make it use `delete[] ptr;`, and using the wrong one is undefined behaviour. – chris May 23 '13 at 01:01

1 Answers1

3

It will automatically use the move constructor if no RVO takes place, so it's all good. You definitely do not want to return a reference, as it would dangle. Do note that no assignment is being done here anyway, though. And as Benjamin points out, now that you've filled in the ellipsis, you need to use std::unique_ptr<int[]> to allocate that sort of memory.

chris
  • 60,560
  • 13
  • 143
  • 205