![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are copy elision and return value optimization?
Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. So if you have some code that is creating objects not being used or don't have side effects,
example
struct MyStruct { MyStruct() {} MyStruct(const MyStruct&) { std::cout << "Copied.\n"; } }; MyStruct f() { return MyStruct(); } int main() { std::cout << "Main\n"; MyStruct obj = f(); }
Output
You could get any of following outputs based on compiler and settings −
Main Main Copied Copied Main Copied
This means fewer objects than you expect can be created, so you also can't rely on a specific number of constructors and destructors being called. You shouldn't have critical logic inside copy/move-constructors or destructors, as you can't rely on them being called.
Advertisements