1

I am having a hard time understanding why std::move() with object literals doesn't work.

Given the following simple code:

#include <memory> 
#include  <vector>

class A{
};

void func(A &&param1){
}

int main()
{
    auto a = std::unique_ptr<A>(new A());
    auto vec = std::vector<std::unique_ptr<A>>{std::move(a)};   //this code does not work!!
    //std::vector<std::unique_ptr<A>> vec;    // but this code works
    //vec.push_back(std::move(a));
    return 0;
}

Since C++20, push_back() is defined as constexpr:

constexpr void push_back( T&& value );

Shouldn't std::move() work the same in both object literal vector initialization and using push_back()?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ovidiu Buligan
  • 2,784
  • 1
  • 28
  • 37
  • 7
    You can move into an initializer_list - the `{}` part - but not move out of it. – BoP Mar 20 '23 at 19:41
  • "*Since C++20, `push_back()` is defined as `constexpr`*" - being `constexpr` just means that it is potentially callable at compile-time, but everything you have shown runs at runtime only. That being said, `push_back()` has supported move semantics since C++11. And on a side note, since C++14, use `std::make_unique()` instead of constructing `std::unique_ptr` directly: `auto a = std::make_unique();` – Remy Lebeau Mar 20 '23 at 21:32

0 Answers0