Named Links rvalue

Please forgive my lack of clarity on this topic. I am trying to create functions to insert a large class into a vector. In this example, I use the ints vector as a large class.

#include <vector>
#include <iostream>
using namespace std;

vector<vector<int>> vectorOfVectors;

void fn(const vector<int> &v) {
    vectorOfVectors.push_back(v);

}
void fn(vector<int> &&v) {
    vectorOfVectors.push_back(std::move(v));
}

int main() {
    vector<int> a({1});
    const vector<int> b({2});
    fn(std::move(a));
    fn(b);
    cout<<b[0];
}

Obviously, I do not want to make a copy whenever possible. My questions:

  • Does this code work correctly?
  • Is there a better way to do this?
  • For the same approach to working with custom classes, do you need to define move constructors?
+4
source share
2 answers

Is this code correct?

Yes. C ++ 11 added for this reason std::vector::push_back(T&&).

Is there a better way to do this?

fn(const vector<int> &v) fn(vector<int> &&v) , v vectorOfVectors. fn , .

template<typename T>
void fn(T &&v) {
    vectorOfVectors.push_back(std::forward<T>(v));
}

++ 11 std::forward. T vector<int>& , v lvalue, vector<int>&& , v r. , vector<int>& && vector<int>&, vector<int>&& && vector<int>&&. , , push_back, lvalue, , rvalue.

, , . ( "" g++ clang++). , , " ".

?

. , , , . , , .

, . , , Foo(const Foo&)=default, . explicit, "".

+7
  • a.
  • . push_back , , emplace_back .

    template<typename... Ts>
    auto fn(Ts &&...ts)
      -> decltype(vectorOfVectors.emplace_back(std::forward<Ts>(ts)...), void())
    {
        vectorOfVectors.emplace_back(std::forward<Ts>(ts)...);
    }
    

    http://melpon.org/wandbox/permlink/sT65g3sDxHI0ZZhZ

3. push_back, , , . , .

+2

Source: https://habr.com/ru/post/1614546/


All Articles