C++Guns – RoboBlog

22.02.2019

C+ Guns: ACPL ownership transfer

Filed under: Allgemein — Tags: — Thomas @ 18:02

acpl::moveOwnership bietet im Gegensatz zu std::move den Vorteil, dass ein move-from const Variablen einen Fehler zur Compilezeit erzeugt.

Zwei Beispiele sollen ownership transfer verdeutlichen.
Daten in ein Type moven und dort speichern.

#include <core/util/functional.hpp>

struct Node {};
struct Edge {};
struct Graph {
    std::vector<Node> nodes;
    std::vector<Edge> edges;

    Graph(std::vector<Node>&& nodes, std::vector<Edge>&& edges) 
    : nodes(acpl::moveOwnership(nodes)), edges(acpl::moveOwnership(edges))
    {
    }
};

void func() {
    std::vector<Node> nodes;
    std::vector<Edge> edges;
    // ... fill nodes and edges
    // graph is the new ownership of nodes and data
    Graph graph(acpl::moveOwnership(nodes), acpl::moveOwnership(edges));
    assert(nodes.empty());
    assert(edges.empty());
}

Daten entweder kopieren oder durch eine Funktion moven.

#include <core/util/functional.hpp>

template<typename Container>
inline std::vector<int> copyOrMove(Container&& x) {
    Container data2(std::forward<Container>(x));
    return data2;
}

void func() {
    std::vector<int> x {1,2,3};
    std::vector<int> copy = copyOrMove(x);
    assert(not x.empty());    
    std::vector<int> moved = copyOrMove(acpl::moveOwnership(x));
    assert(x.empty());    
}

Move von const Variablen ist nicht möglich, da die Variablen geändert werden würden, was nicht möglich ist, weil sie const sind.

void func() {
    const std::vector<int> x {1,2,3};
    std::vector<int> moved = acpl::moveOwnership(x); // error: static assertion failed: Move from const variables dosent make sense
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress