簡體   English   中英

我應該如何確保對move構造函數的調用? (移動語義和右值參考)

[英]How should I ensure the call to the move constructor? (move semantics and rvalue reference)

我有這段代碼

#include <iostream>
#include <vector>

using namespace std;

class ArrayWrapper {
    private:
        int *_p_vals;
        int _size;

    public:
        //default constructor
        ArrayWrapper () : _p_vals( new int[ 64 ] ) , _size( 64 ) {
            cout << "default constructor called\n";
        }

        //constructor 2
        ArrayWrapper (int n) : _p_vals( new int[ n ] ) , _size( n ) {
            cout << "constructor 2 called\n";
        }

        //move constructor
        ArrayWrapper (ArrayWrapper&& other) : _p_vals(other._p_vals), _size(other._size) {  
            cout << "move constructor called\n";
            other._p_vals = nullptr;
            other._size = 0;
        }

        // copy constructor
        ArrayWrapper (const ArrayWrapper& other) : _p_vals( new int[ other._size  ] ) , _size( other._size ) {
            cout << "copy constructor called\n";
            for ( int i = 0; i < _size; ++i )
                _p_vals[i] = other._p_vals[i];
        }

        ~ArrayWrapper () {
            delete [] _p_vals;
        }

        void set_val (std::initializer_list <int> vals) {
            int i = 0;
            for (auto val : vals) {
                _p_vals[i] = val;
                i++;
            }
        }
        void print_val () const {
            for (auto i = 0; i < _size ; i++){
                cout <<_p_vals[i] << ":" ;
            }
            cout << endl;
        }
};

ArrayWrapper getArrayWrapper () {
    ArrayWrapper A(5);
    A.set_val({1,2,3,4,5});
    return A;
}

int main () {
    ArrayWrapper arr {getArrayWrapper()};
    arr.print_val();
    return 0;
}

我試圖確保移動構造函數被調用。 但是使用了一些默認的拷貝構造函數,因為輸出就是這樣

constructor 2 called
1:2:3:4:5:

我正在使用以下g ++版本

g++ (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406

我是否應該使所有構造函數調用都explicit 我不知道這會如何幫助。 有沒有一種方法可以強制程序調用上面編寫的move構造函數和copy構造函數?

感謝評論者,我發現編譯器正在執行返回值優化(RVO),這可以防止對上面編寫的構造函數的調用。 我找到了一種禁用RVO的方法。 g ++中的-fno-elide-constructors開關有效。

暫無
暫無

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

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