簡體   English   中英

“默認”移動構造函數和分配-奇怪的行為

[英]“Defaulted” move constructor and assignment - weird behaviour

因此,我有一個具有兩個成員變量的類的簡單示例。 我已經聲明了一個副本和一個移動構造函數,它們都是= default ,這將迫使編譯器為我生成它們。 現在我的問題是這個。 使用move構造函數(或賦值)時,為什么我移走的對象保持原樣?

例如,如果我有:

myclass obj(4, 5);
myclass obj2 = std::move(4, 5);

據我了解,第二行obj將包含“ nothing”,因為它將被移到obj2 ,它將具有值(4, 5) 我知道我不習慣在這里更正字...

完整代碼:

#include <iostream>
#include <utility>

template<class T1, class T2>
class Pair
{
public:
    T1 first;
    T2 second;

public:
    //CONSTRUCTORS
    constexpr Pair() = default;

    constexpr Pair(const T1& _first, const T2& _second)
        : first(_first), second(_second)
    {}

    constexpr Pair(T1&& _first, T2&& _second)
        : first(std::forward<T1>(_first)), second(std::forward<T2>(_second))
    {}

    constexpr Pair(const Pair&) = default;
    constexpr Pair(Pair&&)      = default;

    //ASSIGNMENT
    Pair &operator=(const Pair&) = default;
    Pair &operator=(Pair&&)      = default;
};

int main()
{
    Pair<int, int> p(1, 2);

    Pair<int, int> p2 = p; //all good, p = {1, 2} and p2 = {1, 2}

    Pair<int, int> p3 = std::move(p); //p = {1, 2} and p3 = {1, 2}
                                    //why isn't p "moved" into p3??
                                    //p should be empty??

    //same thing occurs with the move assignment. why?

    std::cout << p.first << " " << p.second << "\n";
    std::cout << p2.first << " " << p2.second << "\n";
    std::cout << p3.first << " " << p3.second << "\n";
}

實時示例: http//coliru.stacked-crooked.com/a/82d85da23eb44e66

int默認舉動只是一個副本。

默認的move構造函數和move分配將簡單地向所有成員調用std::move 就像副本一樣,默認的副本構造函數會簡單地調用所有成員的副本。

您的代碼是正確的,並且在調用std::move ,通常移動的數據仍然存在。 為什么? 因為std::move在原語上會復制它們。 編譯器不會生成使int變為0代碼,因此它是一個簡單的副本。 但是,如果您對包含更復雜的類型(例如std::vector<int> ,則移動的向量將有效地最終為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM