std move () : How this template function works?

Share the Article

The std::move( ) is a function template which perform static casts. The std::move( ) unconditionally casts its argument (an L-value or R-value) to an R-value. This template function takes a reference to an object (using a universal reference parameter) and it returns a R-value reference to the same object.

Example,

int x = 9; int && y = std::move(x); //Move taking L-value argument //& returning R-value int && z = std::move(4); //Move taking R-value argument //& returning R-value auto up1 = std::make_unique<int>(); std::unique_ptr<int> up2 = std::move(up1); //Move taking unique_ptr //& returning R-value of data

std::move does not move anything but it simply cast its argument to an R-value. Please note that everything happens only in compile time.

The simplest implementation of move is as follows:

template <typename T> typename std::remove_reference<T>::type&& move(T&& param) { using ReturnType = typename std::remove_reference<T>::type&&; return static_cast<ReturnType>(param); }
  • The parameter type is T&& (universal reference), which means it accepts both L-value and R-value arguments.
  • The “&&” part of the function’s return type means that std::move returns only an r-value reference.
  • The function uses typename because, we are using a datatype inside a template class T (dependent type)
using ReturnType = typename std::remove_reference<T>::type&&;

The funciton uses remove_reference because this ensures that whatever is the calling type (L-value or R-value), the return type always correspond to R-value of basic type.

The std::remove_reference template class is part of C++ library, however, we can easily implement this in following way:

template <class T> struct remove_reference { typedef T type; }; template <class T> struct remove_reference<const T> { typedef const T type; }; template <class T> struct remove_reference<T&> { typedef T type; }; template <class T> struct remove_reference<const T&> { typedef const T type; }; template <class T> struct remove_reference<T&&> { typedef T type; }; template <class T> struct remove_reference<const T&&> { typedef const T type; };

Code Example: Demonstration of local implementation of move function

#include <iostream> using namespace std; template <typename T> typename std::remove_reference<T>::type&& my_move(T&& param) { using ReturnType = typename std::remove_reference<T>::type&&; return static_cast<ReturnType>(param); } void check(int& a) //L-value version { cout << "L-value check() called" << endl; } void check(int&& a) //R-value version { cout << "R-value check() called" << endl; } int main() { check(5); //Calls check(&&) int w; check(w); //Calls check(&) check(my_move(w)); //Calls check(&&) return 0; }

The output is:

R-value check() called L-value check() called R-value check() called

Main Funda: std::move( ) does not move anything, it simply cast anything to its correspoding R-value at compile time

Related Topics:

 What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
What is reference collapsing?
How std::move() function works?
How delete keyword can be used to filter polymorphism
Rule of Three

Share the Article

3,755 thoughts on “std move () : How this template function works?

  1. Pingback: 2thomson
  2. I’d like to thank you for the efforts you’ve put in penning this blog. I’m hoping to view the same high-grade content by you later on as well. In fact, your creative writing abilities has encouraged me to get my own blog now 😉

  3. Thanks for all your valuable efforts on this site. Debby really loves carrying out internet research and it is obvious why. I know all concerning the dynamic tactic you offer invaluable tips and hints on your website and even foster contribution from some other people on this situation and our girl is really starting to learn a whole lot. Enjoy the remaining portion of the new year. You are performing a remarkable job.

  4. Thanks for all your valuable efforts on this site. Debby really loves carrying out internet research and it is obvious why. I know all concerning the dynamic tactic you offer invaluable tips and hints on your website and even foster contribution from some other people on this situation and our girl is really starting to learn a whole lot. Enjoy the remaining portion of the new year. You are performing a remarkable job.

  5. 경마사이트는 온라인경마사이트,실시간경마사이트,인터넷경마사이트,안전한경마사이트,사설경마사이트,한국경마,일본경마,스크린경마 등 먹튀검증 업계 1위 경마사이트

  6. 우리 업체는 인증된 업체입니다. 정품을 저렴한 가격에 비밀포장, 택배비 무료, 당일 배송을 원칙으로 합니다. 오후 4시까지 입금이 확인되면 빠르게 받아보실 수 있습니다. 그 이후에도 확인이 되면 당일배송이 가능합니다. 그 외에 다른 문의사항 있으시면 24시간 친절한 상담원이 답변해드리고 있습니다.
    저희가 판매하는 제품은 모두 정품입니다. 인증되지 않은 제품은 판매하지 않습니다.
    오후 4시까지 입금이 확인되면 당일배송이 가능합니다. 프라이버시를 위한 불투명한 3중 포장으로 배송해드리고 있습니다. 할인된 금액과 이벤트로 가성비있는 제품을 받아보세요.
    7일 24시간 365일 연중무휴 대기중입니다.

  7. 100% 정품 판매 업체
    VIAGRA – CIALIS
    처방전 필요없는 비아그라 | 처방전 없이 시알리스 구매

    비아그라 처방전 없이 살 수 있나요? 네! 가능합니다.
    비아그라와 시알리스를 처방전 없이 구매하세요. 100% 정품 판매.

    발기부전 치료를 위한 대표적인 2가지 발기부전 치료 약.

    안전하고 비밀을 보장한 채 빠르고 신속한

    비아그라 퀵 배송 전문!

    1 : 1 카카오톡 문의 가능. 신속한 답변.

    다양한 상품 1 + 1 이벤트!

  8. 비아그라 구입비아그라구매 비아그라판매 비아그라후기 비아그라처방 비아그라판매처 비아그라가격 비아그라구입처 비아그라정품 비아그라효과 비아그파는곳 비아그라복용법 비아그라부작용 비아그라종류 비아그라사이트 비아그라구입방법 비아그라팝니다비아그라 구입비아그라구매 비아그라판매 비아그라후기 비아그라처방 비아그라판매처 비아그라가격 비아그라구입처 비아그라정품 비아그라효과 비아그파는곳 비아그라복용법 비아그라부작용 비아그라종류 비아그라사이트 비아그라구입방법 비아그라팝니다

  9. 비아그라 파는곳,온라인 약국 비아그라,비아그라 구매,비아그라 퀵배송,비아그라 구입처 모든 상품100% 정품임을 보장하며 모든 배송은 비밀배송 퀵배송 가능합니다

  10. 안전한 비아그라 퀵배송은 소중한 고객님의 프라이버시를 위한 비밀보장 및 배송해드립니다. 당일 배송.오후 2시 이전 입금시 100%당일 무료 배송 원칙을 합니다.

  11. 비아그라파는곳,비아그라 파는곳,비아그라 구입,비아그라 퀵배송, 비아그라구매, 시알리스 파는​곳,,비아그라 구입방법,온라인 비아그라판매스토어,비아그라 구입,발기부전치료제,비아그라 처방전없이구입,비아그라 판매사이트,비아그라,시알리스,레비트라,팔팔정,온라인 비아그라 구매 구입 사이트 비아스토어 입니다.
    100%정품 국내 최저가로 비아스토어에서 만나 보세요!

  12. 비아그라는 발기부전으로 어려움을 겪는 남성들에게 큰 힘이 되어주는 약품이다. 비아그라는 주로 발기부전 치료제로 이용되지만, 다른 용도로 이용하는 경우도 있다. 예를 들어, 비아그라는 폐고혈압을 치료하기 위한 목적으로도 이용된다. 또한 고산병 치료제로도 이용할 수 도 있다.

  13. 비아그라는 발기부전의 대표적인 약이지만 복용하는 사람의 건강상태와 유전적 요인등으로 작은 부작용들이 발생할 수 있기 때문에 의사와 상담한 후 적정량의 비아그라를 복용하는 것이 바람직하다

  14. 요요약국에서는 처방전 없이 저렴한 가격으로 100%정품을 구매를 할 수가 있습니다. 비아그라 구입을 원한다면 요요약국으로 오세요. 쉽게 100%정품을 구매 할수가 있습니다. 초보자로도 어렵지 않게 비아그라 구입을 할수가 있습니다.

  15. 먹튀검증 검증 업계 1위 경마사이트만 소개합니다
    안전하고 경마사이트 에서 실시간경마 를 즐기실 수 있습니다.
    인터넷이 있는곳이라면 어디서든 실시간경마를 영상으로 ​편하게 베팅하세요.

  16. 모바­일경마의 진수 최적화된 환경에서

    어디서든 간편하게 경마사이트 를 이용하세요.

    검빛 경마에서도 검증이 완료된 안전한 인터넷경마 만을 추천합니다.

    온라인경마는 반드시 믿을 수 있는곳에서 이용하여야합니다.

    일본경마사이트 까지 제공하고 있습니다.

  17. 경마사이트는 온라인경마사이트,실시간경마사이트,인터넷경마사이트,안전한경마사이트,먹튀검증 경마사이트,사설경마사이트,한국경마,일본경마,스크린경마 등 먹튀검증 업계 1위 경마사이트만 추천하며 전세계 경마사이트 관련 정보를 공유합니다.다양한 이벤트들이 제공되고 있으며 먹튀검증 경마사이트만을 추천합니다.

  18. 모바­일경마의 진수 최적화된 환경에서

    어디서든 간편하게 경마사이트 를 이용하세요.

    검빛 경마에서도 검증이 완료된 안전한 인터넷경마 만을 추천합니다.

    온라인경마는 반드시 믿을 수 있는곳에서 이용하여야합니다.

    일본경마사이트 까지 제공하고 있습니다.

  19. Thanks for the guidelines shared on your own blog. Another thing I would like to express is that losing weight is not all about going on a fad diet and trying to shed as much weight as you can in a couple of weeks. The most effective way to lose weight naturally is by using it slowly and following some basic points which can enable you to make the most through your attempt to lose fat. You may realize and be following most of these tips, but reinforcing information never does any damage.

  20. It is perfect time to make some plans for the future and it is time
    to be happy. I’ve read this post and if I could I desire to suggest
    you few interesting things or tips. Perhaps you could write next articles referring to this article.
    I want to read more things about it!

  21. Please let me know if you’re looking for a article author for your blog.
    You have some really good articles and I feel I
    would be a good asset. If you ever want to take some of the load
    off, I’d really like to write some material for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested.

  22. Greetings, I do think your blog could be having internet browser
    compatibility problems. When I take a look at your web site in Safari, it looks
    fine however when opening in I.E., it’s got some overlapping issues.
    I merely wanted to give you a quick heads up! Aside from that,
    fantastic blog!

  23. It’s the best time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I desire to suggest you some interesting things or tips.
    Perhaps you could write next articles referring to this
    article. I desire to read even more things about it!

  24. Good day! I could have sworn I’ve visited this website before but after browsing through
    some of the articles I realized it’s new to me. Anyhow, I’m definitely pleased I came across
    it and I’ll be book-marking it and checking back often!

  25. Its like you read my mind! You appear to know so much about this, like
    you wrote the book in it or something. I think that you can do with some pics to drive the
    message home a bit, but other than that, this is great blog.
    A fantastic read. I’ll definitely be back.

  26. Thanks for your helpful post. Through the years, I have been able to understand that the actual symptoms of mesothelioma are caused by this build up associated fluid between your lining of the lung and the chest muscles cavity.

  27. There are a few interesting points over time in this article but I do not determine if every one of them center to heart. There’s some validity but I am going to take hold opinion until I check into it further. Excellent write-up

  28. Fantastic goods from you, man. I have understand
    your stuff previous to and you’re just too fantastic.
    I really like what you have acquired here, certainly like what you are
    stating and the way in which you say it.

  29. Hi there, I do think your blog may be having browser compatibility problems. When I look at your web site in Safari, it looks fine however when opening in I.E., it has some overlapping issues. I just wanted to give you a quick heads up! Apart from that, excellent site!

  30. Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  31. As I am looking at your writing, slotsite I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

  32. You actually make it seem so easy along with your presentation however I to find this topic to be actually one thing that I feel I might never understand. It seems too complicated and extremely vast for me. I am looking ahead in your next publish, I?¦ll try to get the hold of it!

  33. What i do not realize is actually how you are now not really much more neatly-liked than you may be right now. You’re very intelligent. You already know thus considerably in terms of this topic, produced me for my part consider it from a lot of varied angles. Its like women and men are not interested except it is one thing to do with Woman gaga! Your own stuffs great. At all times deal with it up!

  34. Please let me know if you’re looking for a article author for your weblog. You have some really good articles and I think I would be a good asset. If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Thank you!

  35. 1 letter 127, p priligy amazon canada The IBIS II trial, also comparing adjuvant Tamoxifen to Anastrazole, did not find a significant difference in breast cancer recurrences between the two cohorts, but suggested that Anastrozole resulted in fewer ER invasive tumor recurrences compared to Tamoxifen 70

  36. เกม สล็อต แตก ง่าย แตกจริง แจกหนัก ต้องเล่นที่นี่เลย PG-SLOT.GAME เว็บเกมสล็อตออนไลน์จากค่ายเกมสล็อตออนไลน์อันดับ 1 ตลอดกาลอย่าง PG SLOT ที่ดีที่สุดคนเล่นมีมากที่สุดในปี 2022

  37. โปรโมชั่น pg slot รวมโปรสล็อต PG โปรโมชั่นดีๆสุดพิเศษและก็ร้อนแรงมาเสนอแนะสำหรับคุณ สำหรับสาวกสล็อตตัวจริงต้องห้ามพลาดกับโปรโมชั่นที่พวกเราเตรียมความพร้อมมายกให้คุณทุกวัน

  38. I was pretty pleased to find this web site. I need to to thank you for your time just for this wonderful read!!
    I definitely liked every little bit of it and I have you book-marked to check out
    new information on your site.

    my page … tracfone 2022

  39. ทาง เข้า xo เกมสล็อตออนไลน์ที่เเตกง่ายที่สุดในบรรดาเว็บสล็อตต้องมาเล่นกับเรา pgslot-th.com มีเกมให้เลือกหลากหลายรูปแบบภาพการ์ตูนสวย เด่นกว่าใครต้องเกมของระบบฝากถอนง่ายมาก

  40. pg slot autoทาง เข้า pg slot auto หรือ pg-slot.game เกมพีจีสล็อต pg สล็อตออนไลน์ 3 มิติ (pg slot auto) จากค่าย pg slot และ บาคาร่าออนไลน์ ที่มาในรูปแบบใหม่เป็นเกมส์ยอดนิยม

  41. When I read an article on this topic, baccarat online the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

  42. Two recent comparative effectiveness reviews provide the most comprehensive, albeit contradictory, assessments to date 15, 16 tamoxifen cost These receptor proteins serve as a bridge between the cargo bacteria and LC3 on the membranes of the nascent autophagosomes

  43. Hui is lead author of a study, published in Cancer, on clinical signs stromectol in canada Taken together, these results, thus, show that testosterone secreted by the testes acts perinatally, after being aromatized into estradiol and, thus, stimulating estradiol receptors, to masculinize and or defeminize the neural substrate that controls sexual behavior

  44. ak88bet is the most suitable online casino, original and not copied. from another website ready to feel Have fun, fun with exciting games and earn money with pg slot-th.com. Easy to break. Get real money.

  45. These also show decreased expression of genes that are down regulated upon acquired endocrine resistance MASSARWEH_ENDOCRINE_RESISTANCE_DN and also the group 4 set of Creighton endocrine therapy resistance which were found to increase in models of endocrine therapy resistance Creighton et al generic cialis 20mg Loomus GN, Aneja P, Bota RA

  46. My brother suggested I might like this website. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  47. An intriguing discussion is worth comment. I do believe that
    you should write more about this subject, it might not be a taboo subject but usually
    people do not talk about these subjects. To the next! Best wishes!!

  48. I feel this is one of the such a lot vital info for me.
    And i’m satisfied reading your article. But should remark on some normal things, The website style
    is great, the articles is truly excellent : D. Just right activity, cheers

  49. Additionally, like all health-related content on this website, this Hims ED review was thoroughly vetted by one or more members of our Medical Review Board for accuracy buy online cialis Study Country Age median Therapy in experimental group Therapy in control group Sample size Method Time of therapy weeks Dosage mg mg Main inclusion criteria Study design Experimental Control Francesco M 2013 Multicenter 58

  50. Do you have a spam problem on this blog; I also am a
    blogger, and I was wondering your situation; many of us have created some nice procedures and we are looking to exchange methods with other folks,
    why not shoot me an email if interested.

  51. I think this is among the most vital information for me.

    And i am glad reading your article. But wanna remark
    on few general things, The website style is wonderful,
    the articles is really nice : D. Good job, cheers

    my blog post: special

  52. Hi there! Someone in my Myspace group shared this website with us so I came to check it out.
    I’m definitely enjoying the information. I’m bookmarking
    and will be tweeting this to my followers! Outstanding blog and brilliant design and style.

  53. I’m amazed, I have to admit. Seldom do I encounter a blog that’s
    both equally educative and amusing, and without a doubt, you’ve
    hit the nail on the head. The issue is something which not
    enough folks are speaking intelligently about. Now i’m very happy that I came across this in my hunt for something
    concerning this.

  54. Definitely believe that which you stated. Your favourite justification appeared to be at the
    net the easiest thing to be mindful of. I say to you, I definitely get irked at the same time as folks consider worries that they plainly do not know
    about. You controlled to hit the nail upon the highest as well as outlined out the entire thing with no need side effect ,
    people could take a signal. Will probably be back to get more.
    Thank you

  55. Great blog you have here but I was curious if you knew of any forums
    that cover the same topics discussed here? I’d really love
    to be a part of community where I can get comments from other knowledgeable
    people that share the same interest. If you have any suggestions,
    please let me know. Thanks a lot!

  56. Hi it’s me, I am also visiting this site daily, this web page is truly fastidious and the viewers are in fact sharing pleasant thoughts.

  57. I’ve been exploring for a bit for any high-quality articles
    or blog posts in this kind of space . Exploring in Yahoo I finally stumbled
    upon this web site. Studying this information So i’m satisfied to convey that I have an incredibly excellent uncanny feeling I found out just
    what I needed. I most surely will make certain to don?t overlook this
    site and provides it a look on a continuing basis.

  58. Siteye üye olmak kayıt formunda royalcasino üyelik bilgilerinizi doldurmanız gerekir. Bu alanda kişisel bilgilerinizi girmelisiniz. Adınız, soyadınız ve doğum tarihiniz gibi çeşitli bilgileri doğru bilgilerle doldurarak diğer adıma geçebilirsiniz. Diğer adımda sizden kullanıcı adınızı ve şifrenizi belirlemeniz istenir. Bu alan üzerinden bilgilerinizi sağlıklı bir şekilde doldurarak diğer işleme geçebilirsiniz. Diğer işlemlerdeyse sizden iletişim bilgileriniz istenir. Bu alanı doğru doldurursanız siteyle alakalı önemli duyuruları ilk siz öğrenmiş olursunuz. Bunu yapabilmek için kendi iletişim bilgilerinizi doğru bilgilerle doldurmanız tavsiye edilir. Site içerisinde yer alan kampanyaları ve fırsatları bilerek buna göre hareket edebilirsiniz. Tüm işlemleri tamamladıktan sonra kuralları ve şartları kabul ederek siteye başarıyla üye olabilirsiniz. Royalcasino Yatırım Kampanyaları

  59. wonderful put up, very informative. I ponder why the other experts of this sector don’t notice this. You should proceed your writing. I’m sure, you have a great readers’ base already!