你的位置:睿鑫网络 >> 编程 >> 编程语言 >> VC.NET >> 详细内容 在线投稿

VC10中的C++0x特性 part 2(2):右值引用

排行榜 收藏 打印 发给朋友 举报 来源: 网络   发布者:未知
热度0票  浏览0次 时间:2010年5月31日 18:32

本文为 Part 2 第二页。

move 语意:从 lvalue 移动

现在,如果你喜欢用拷贝赋值函数来实现你的拷贝构造函数该怎样做呢,那你也可能试图用 move 拷贝赋值函数来实现 move 构造函数。这样作是可以的,但是你得小心。下面就是一个错误的实现:

C:Temp>type unified_wrong.cpp

#include

#include

#include

using namespace std;

class remote_integer {

public:

remote_integer() {

        cout << "Default constructor." << endl;

        m_p = NULL;

    }

    explicit remote_integer(const int n) {

        cout << "Unary constructor." << endl;

        m_p = new int(n);

    }

    remote_integer(const remote_integer& other) {

        cout << "Copy constructor." << endl;

        m_p = NULL;

        *this = other;

    }

#ifdef MOVABLE

    remote_integer(remote_integer&& other) {

        cout << "MOVE CONSTRUCTOR." << endl;

        m_p = NULL;

        *this = other; // WRONG

    }

#endif // #ifdef MOVABLE

    remote_integer& operator=(const remote_integer& other) {

        cout << "Copy assignment operator." << endl;

        if (this != &other) {

            delete m_p;

            if (other.m_p) {

                m_p = new int(*other.m_p);

            } else {

                m_p = NULL;

            }

        }

        return *this;

    }

#ifdef MOVABLE

    remote_integer& operator=(remote_integer&& other) {

        cout << "MOVE ASSIGNMENT OPERATOR." << endl;

        if (this != &other) {

            delete m_p;

            m_p = other.m_p;

            other.m_p = NULL;

        }

        return *this;

    }

#endif // #ifdef MOVABLE

    ~remote_integer() {

        cout << "Destructor." << endl;

        delete m_p;

    }

    int get() const {

        return m_p ? *m_p : 0;

    }

顶:0 踩:0
对本文中的事件或人物打分:
当前平均分:0 (0次打分)
对本篇资讯内容的质量打分:
当前平均分:0 (0次打分)
上一篇 下一篇

网络资源