Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr swap doesn't work

My code is:

#include <memory>
#include <vector>

struct Core{
    Core(int n){} };

int main() {
    int base;
    std::vector<std::unique_ptr<Core>> cores;

    cores.push_back( std::move(std::unique_ptr<Core>(new Core(base))) );
    cores[0].swap(std::unique_ptr<Core>(new Core(base)));

    return 0;
}

And I get this error:

||=== Build: Release in Test (compiler: GNU GCC Compiler) ===|

In function 'int main()' error: no matching function for call to 'std::unique_ptr<Core>::swap(std::unique_ptr<Core>)'

note: candidate is:

note: void std::unique_ptr<_Tp,_Dp>::swap(std::unique_ptr<_Tp,_Dp>&) [with_Tp = Core; _Dp = std::default_delete<Core>]

note: no known conversion for argument 1 from 'std::unique_ptr<Core>' to 'std::unique_ptr<Core>&'

like image 996
Sheed Avatar asked Jun 04 '26 15:06

Sheed


1 Answers

You can not swap with a temporary object (an rvalue) like this:

cores[0].swap(std::unique_ptr<Core>(new Core(base))); // error

But a temporary can swap with a named object (lvalue) like this

std::unique_ptr<Core>(new Core(base)).swap(cores[0]); // but this works

Alternatively you can just set the value directly:

cores[0] = std::unique_ptr<Core>(new Core(base));

Or (better) using std::make_unique

cores[0] = std::make_unique<Core>(base);

You pass the parameters for the object's constructor directly to the std::make_unique function.

And if you must use new there is always the std::unique_ptr::reset function:

cores[0].reset(new Core(base));
like image 58
Galik Avatar answered Jun 06 '26 05:06

Galik