Move Semantics (c++11)

Source: Internet
Author: User

/*
* Compile with:
* g++ Move_test.c-o move_test-std=c++11-g-fno-elide-constructors
*-fno-elide-constructors disabled the return value optimize.
*/
#include <iostream>
#include <utility>


Class A {
Public
A (void)
{
a = new int;
Std::cout << "Constructing (normal) A" << (void *) this << Std::endl;
}
A (const Class A &other)
{
Std::cout << "Constructing (copy) A" << (void *) this << Std::endl;
}
A (Class A &&other)
{
Std::cout << "Constructing (move) A" << (void *) this << Std::endl;
A = OTHER.A;
OTHER.A = NULL;
}


~a (void)
{
Std::cout << "destructing A" << (void *) this << Std::endl;
Delete A;
}
void set (int i)
{
*a = i;
}
int get (void)
{
return *a;
}
Private
int *a;
};


Class B {
Private
Class A;
Public
B (void)
{
Std::cout << "Constructing (normal) B" << (void *) this << Std::endl;
}
B (Const class B &other)
: A (OTHER.A)
{
Std::cout << "Constructing (copy) B" << (void *) this << Std::endl;
}
B (Class B &&other)
: A (Std::move (OTHER.A))
{
Std::cout << "Constructing (move) B" << (void *) this << Std::endl;
}
~b (void)
{
Std::cout << "destructing B" << (void *) this << Std::endl;
}
void set (int i)
{
A.set (i);
}
int get (void)
{
A.get ();
}
};


Class B func (void)
{
Class B b;
B.set (23);
Std::cout << "function seperating ..." << Std::endl;
Std::cout << b.get () << Std::endl;
return b;
}


int main (void)
{
Class B B (func ());




Std::cout << b.get () << Std::endl;
B.set (' W ');
Std::cout << "seperating ..." << Std::endl;
Std::cout << b.get () << Std::endl;


return 0;

}


Running results:

Constructing (normal) a0xbf965d1c
Constructing (normal) b0xbf965d1c
function seperating ...
23
Constructing (move) a0xbf965d4c
Constructing (move) b0xbf965d4c
Destructing b0xbf965d1c
Destructing a0xbf965d1c
Constructing (move) a0xbf965d48
Constructing (move) b0xbf965d48
Destructing b0xbf965d4c
Destructing a0xbf965d4c
23
Seperating ...
119
Destructing b0xbf965d48
Destructing a0xbf965d48

Move Semantics (c++11)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.