U++ framework
Do not panic. Ask here before giving up.

Home » Community » Coffee corner » C++11
Re: C++11 [message #38144 is a reply to message #38143] Sun, 02 December 2012 18:47 Go to previous messageGo to previous message
Lance is currently offline  Lance
Messages: 656
Registered: March 2007
Contributor
And any object can be std::move()'ed to become moveable, no matter it's a temporary or not.

#include <iostream>
#include <string>
#include <algorithm>
#include <new>

using namespace std;

struct S
{
	S(){}
	S(const S& rhs) : text(rhs.text){}
	S(S&& rhs){
		struct T{ char _[sizeof(S)]; };
		std::swap(reinterpret_cast<T&>(*this), 
			reinterpret_cast<T&>(rhs)
		);
	}

	S& operator=(const S& rhs)
	{
		this->~S();
		return *new(this)S(rhs);
	}

	S& operator=(S&& rhs)
	{
		this->~S();
		// std::move() is necessary even when rhs is declared as temoprary
		return *new(this)S(move(rhs));
	}
	
	string text;
		
};
ostream& operator<<(ostream& os, const S& s)
{
	return os<<s.text<<endl;
}



S global;



int main()
{
	global.text="This is the global text";
	cout<<global;
	
	S a;
	a.text="This is object a";
	
	// 
	//
	S b(a);
	cout<<"after S b(a), now <b> is:"<<b<<"and <a> is:"<<a;
	
	S c(std::move(global)); // use move constructor
	cout<<"after S c=std::move(global), now <c> is:"<<c<<"and <global> is:"<<global;
	
}
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: live session Prague 8.3.2013
Next Topic: Have Visual Studio? Looking for prebuilt SDL 2.0
Goto Forum:
  


Current Time: Fri Oct 09 19:03:40 GMT+2 2026

Total time taken to generate the page: 0.00864 seconds