How to enforce copy elision, why it won't work with deleted copy constructor?

前端 未结 3 405
孤独总比滥情好
孤独总比滥情好 2020-12-01 17:58

I have an uncopiable class. Copying this would be problematic. I want to guarantee that it won\'t be ever copied, so I made its copy constructor deleted

3条回答
  •  猫巷女王i
    2020-12-01 18:29

    Until C++17 copy elision is an optimization the compiler is not required to do, so classes must be copyable since the compiler might want to copy (even if it actually does not). In C++17 copy elision will be guaranteed in many cases and then classes won't need copy ctors.

    See also:

    http://en.cppreference.com/w/cpp/language/copy_elision

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html

    https://herbsutter.com/2016/06/30/trip-report-summer-iso-c-standards-meeting-oulu/ (the bit about "Guaranteed copy elision")

    You could perhaps use the old trick of declaring the copy constructor in your class but not actually implement it? That should please the compiler as long as it does not actually invoke the copy ctor. I didn't test that, but I believe it should work for your case until C++17 arrives.

提交回复
热议问题