C 11: Move Semantics - MITK

2y ago
4 Views
2 Downloads
813.80 KB
20 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Abby Duckworth
Transcription

5/10/2016C 11:Move SemanticsSandy EngelhardtMITK Bugsquashing Seminar, March 2016

Welcome to the DKFZ!

Sandy EngelhardtE 1305/10/2016 Page3Rvalue References I Rvalue references is a small technical extension to the C language allow programmers to avoid logically unnecessary copying and toprovide perfect forwarding functions primarily meant to aid in the design of higher performance and morerobust libraries. a new category of reference variables for unnamed objects(temporaries) typical examples of unnamed objects are return values of functions ortype-casts

Sandy EngelhardtE 1305/10/2016 Page4Rvalue References II// standard C lvalue reference variablestd::string& ref;// C 11 rvalue reference variablestd::string&& rrstr; lvalue – may appear on the left hand side of an assignment,represents storage region locator value all the rest is non-lvalue or rvalue (because can appear on theright hand side of assignment only)An rvalue reference behaves just like an lvalue reference except thatit can bind to a temporary (an rvalue), whereas you can not bind a(non const) lvalue reference to an rvalue.

Sandy EngelhardtE 1305/10/2016 Page5Copying Objects Hitherto, copying has been the only the object is never going to be usedmeans for transferring a state fromone object to another(* state of object collective set of its nonstatic data members‟ values) Formally, copying causes a targetobject t to end up with the samestate as the source s, withoutmodifying s. Using the value of a temporaryobject e.g. these to initializeanother object or to assign itsvalue, does not require a copy:for anything else, and thus, its valuecan be moved into the destinationobject.

Sandy EngelhardtE 1305/10/2016 Page6Example: Copystring func(){string s;//do something with s herereturn s;}string mystr func();When func() returns, C constructs a temporary copy of s on thecaller‟s stack memory.2. s is destroyed and the temporary is used for copy-constructingmystr1.3.the temporary itself is destroyed

Sandy EngelhardtE 1305/10/2016 Page7Copy vs. Move Copying a string requires theallocation of dynamic memory andcopying the characters from thesource. Moving (new!) achieves the sameeffect without so many copies anddestructor calls along the way. Moving a string is almost free; itmerely assigns the values of thesource‟s data members to thecorresponding data members ofthe target. Move operations tend to be fasterthan copying because they transferan existing resource to a newdestination, whereas copyingrequires the creation of a newresource from scratch.

Sandy EngelhardtE 1305/10/2016 Page8An addition to the fabulous 4 Default constructor Copy constructor Copy assignment operator Destructor C 11 introduces two new special member functions: themove constructor and the move assignment operator. If a class doesn‟t have any user-declared special memberfunctions, C declares its remaining five (or six) specialmember functions implicitly, e.g.class S{};

Sandy EngelhardtE 1305/10/2016 Page9Move Constructor A move constructor looks like this://C 11 move constructorMyClass::MyClass(MyClass&& other); It doesn‟t allocate new resources. Instead, it pilfers other„sresources and then sets other to its default-constructedstate. The move constructor is much faster than a copyconstructor because: it doesn‟t allocate memory It doesn‟t copy memory buffers

Sandy EngelhardtE 1305/10/2016 Page10Example Move Constructorclass MemoryPage{size t size;char * buf;public://constructorexplicit MemoryPage(int sz 512):size(sz), buf(new char [size]) {}//destructor MemoryPage(){delete[] buf;}//C 03 copy constructorMemoryPage(const MemoryPage&);//C 03 assignment operatorMemoryPage& operator (const MemoryPage&);};//C 11 move constructorMemoryPage(MemoryPage&& other):size(0), buf(nullptr){// pilfer other’s resourcesize other.size;buf other.buf;// reset otherother.size 0;other.buf nullptr;}//C 11 move assignment operatorMemoryPage&MemoryPage::operator (MemoryPage&&other){ }

Sandy EngelhardtE 1305/10/2016 Page11Examples// function returning a MemoryPage objectMemoryPage fn();// default constructorMemoryPage foo;// copy constructorMemoryPage bar foo;// move constructorMemoryPage baz fn();// copy assignmentfoo bar;// move assignmentbaz MemoryPage();

Sandy EngelhardtE 1305/10/2016 Page12STL The overload resolution rules of C 11 were modified tosupport rvalue references Standard Library functions such asvector::push back()now define two overloadedversions: const T&for lvalue argumentsT&&for rvalue argumentsAll containers are “move-aware”New algorithms: move, move forwardNew iterator adaptor: move iteratorOptimized swap for movable types

Sandy EngelhardtE 1305/10/2016 Page13Hands-on Example The following program populates a vector with MemoryPageobjects using two push back()calls:#include vector using namespace std;#include vector using namespace std;int main(){vector MemoryPage vm;int main(){vector MemoryPage vm;MemoryPage mp1(1024);vm.push back(mp1);vm.push back(MemoryPage(1024));vm.push back(MemoryPage(2048));} arguments are rvalues:push back(T&&)is calledpush back(T&&) moves the resources from the argument intovector„s internal MemoryPage objects using MemoryPage„smove constructor. In older versions of C , the same programwould generate copies of the argument since the copyconstructor of MemoryPage would be called instead.} arguments are lvalues:push back(const T&)is called

Sandy EngelhardtE 1305/10/2016 Page14lvalue --- to --- rvalue You can enforce the selection of push back(T&&)by casting an lvalue to an rvalue reference using static cast:// calls push back(T&&)vm.push back(static cast MemoryPage&& (mp)); Alternatively, use the new standard function std::move()for the same purpose:// calls push back(T&&)vm.push back(std::move(mp));

Sandy EngelhardtE 1305/10/2016 Page15What happens to a moved-from object?o1move-from objecto2move-to object state is unspecified, though valid !assumption: object no longer owns any resources andits state is similar to that of an empty (as ifdefault-constructed) object (though valid)

Sandy EngelhardtE 1305/10/2016 Page16Conclusion It may seem as if push back(T&&) is always the bestchoice because it eliminates unnecessary copies.Remember that push back(T&&)empties its argument.If you want the argument to retain its state after apush back()call, stick to copy semantics. Generally speaking, don‟t rush to throw away the copyconstructor and the copy assignment operator !!

Sandy EngelhardtE 1305/10/2016 Page17References ignment-operator/ /2006/n2027.html ences-and-move-semantics https://www.youtube.com/watch?v emantics.html http://www.cplusplus.com/doc/tutorial/classes2/

Thank youfor your attention!Further information on www.dkfz.de

Sandy EngelhardtE 1305/10/2016 Page19Further reading: Move Assignment Operator C& C::operator (C&& other);//C 11 move assignmentoperatorA move assignment operator is similar to a copy constructor exceptthat before pilfering the source object, it releases any resources thatits object may own. The move assignment operator performs fourlogical steps:1. Release any resources that (*this) currently owns.2. Pilfer other„s resource.3. Set other to a default state.4. Return (*this).

Sandy EngelhardtE 1305/10/2016 Page20Further reading: Example MoveAssignment Operator //C 11 move assignment operatorMemoryPage& MemoryPage::operator (MemoryPage&& other){if (this! &other){// release the current object’s resourcesdelete[] buf;size 0;// pilfer other’s resourcesize other.size;buf other.buf;// reset otherother.size 0;other.buf nullptr; }return *this;}

C& C::operator (C&& other);//C 11 move assignment operator A move assignment operator is similar to a copy constructor except that before pilfering the source object, it releases any resources that its object may own. The move assignment operator performs four logical steps:

Related Documents:

Formal Specification [Best – E.g. Denotational Semantics– RD Tennent, Operational Semantics, Axiomatic Semantics] E.g. Scheme R5RS, R6RS Denotational Semantics Ada83 – “Towards a Formal Description of Ada”, Lecture Notes in Computer Science, 1980. C Denotational Semantics

iomatic truths in a programming language. Denotational semantics involves modeling programs as static mathematical objects, namely as set-theoretic functions with speci c properties. We, however, will focus on a form of semantics called operational semantics. An operational semantics is a mathematical model of programming language execu-tion.

Sep 08, 2008 · What is semantics, what is meaning Lecture 1 Hana Filip. September 8, 2008 Hana Filip 2 What is semantics? Semantics is the study of the relation between form and meaning –Basic observation: language relates physical phenomena (acoustic blast

Course info (cont.) This course is an introduction to formal semantics Formal semantics uses formal/mathematical/logical concepts and techniques to study natural language semantics Topics of this course: quantification Tentative plan Lecture 1: Truth-conditions, compositionality Lecture

Formal semantics: The meaning of an utterance depends upon its form, i.e., its linguistic structure. The tools used to account for the meanings of utterances are formal mathematical tool. Truth conditional semantics. Model theoretic semantics. Ph

Computational semantics is an interdisciplinary area combining insights from formal semantics, computational linguistics, knowledge representation and automated reasoning. The main goal of computational semantics is to find techniques for automatically con-structing semantic representation

Introduction 1 Introduction 2 Meaning 3 Types and Model Structure 4 Montague Semantics 5 Phenomena at the Syntax-Semantics Interface 6 Abstract Categorial Grammars 7 Underspeci cation 8 Discourse 9 Selected Bibliography Sylvain Pogodalla (LORIA/INRIA) Computational Semantics

In the midst of Michel’s awakening to the sensuous, sensual existence, to the Dionysian world in nature and himself, he observes: [Marceline] led the way along a path so odd that I have never in any country seen its like. It meanders indolently between two fairly high mud walls; the shape of the gardens they enclose directs it leisurely course; sometimes it winds; sometimes it is broken; a .