簡體   English   中英

了解此示例中的移動構造函數行為

[英]understand the move constructor behavior in this example

我正在學習C ++ 11中的移動語義。 我寫了一個小程序來測試移動語義的行為。 但它沒有像我預期的那樣表現,有人能解釋我為什么嗎?

#include<iostream>

using namespace std;


class Vector
{
public:
    Vector()
    {
    cout << "empty Ctor"<<endl;
    array = new int[10];
    size = 10;
    }

    Vector(int n)
    {
    array = new int[n];
    size = n;
    for (int i=0; i<size; ++i)
        array[i] = i;
    cout << "Ctor"<<endl;
    }

    Vector(const Vector& v):size(v.size)
    {
    array = new int[size];
    for (int i=0; i<size; ++i)
        array[i] = v.array[i];
    cout << "copy"<<endl;
    }

    Vector(Vector&& v):size(v.size)
    {
    array = v.array;
    v.array = nullptr;
    cout << "move"<<endl;

    }

    ~Vector()
    {
    delete array;
    }

private:
    int* array;
    int size;

};

int main() {
    Vector v(10); //print Ctor. (as expected)
    Vector v1(std::move(v)); //print move. (as expected)
    Vector v2(*(new Vector(2)));  //print Ctor, copy. (I expect Ctor, move)
    Vector v3(Vector(2)); //print only Ctor. (I expect Ctor, move)

}

那么,為什么印刷品不符合我的預期。 因為我認為傳遞給v2和v3的值都是Rvalue。 而對於v3,為什么它只打印Ctor而不打印“移動”或“復制”

Vector v2(*(new Vector(2)));

new Vector(2)是一個右值,但取消引用它會產生左值,因此復制而不是移動。

Vector v3(Vector(2));

由於不需要臨時Vector ,編譯器將省略該副本。 您的編譯器可能有一個標志來禁用復制省略,以便您可以看到其他移動,例如GCC和Clang中的-fno-elide-constructors elide -fno-elide-constructors

暫無
暫無

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

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