简体   繁体   中英

Under what conditions does C++ optimize out constructor calls?

I'm writing a class for Matrix arithmetic, and one feature I'm implementing is that you can "slice" a matrix and get another matrix back, but done such that the returned matrix references the parent's memory. This is very useful if you want to things like get a subsection of a matrix or add a vector to a column or things like that.

However, I wanted to implement it so that if the returned matrix is assigned or copied, the aliasing is broken and the memory is copied, so that you can't easily pass an aliased matrix around forever.

In playing with this, I have something like this:

matrix B = A.slice(1,1);  

A.slice(1,1) returns a sub-matrix of A (offset 1 row and 1 column). I implemented the = operator to break the aliasing, but to my chagrine, it isn't called when doing this, even with -O0 on. Similarly:

matrix B(A.slice(1,1)); 

Doesn't call the copy constructor (also written to break aliasing). The only thing that works is:

matrix B; B = A.slice(1,1);

My question is, obviously since I'm initializing B directly from A in the first two examples, it's taking some sort of shortcut, while I explicitly create B first in the last example and then assign A.slice(1,1) to it.

Can someone provide me with some insight into what the rules are in cases like these for when copy constructors and assignment operators are called?

This is called copy elision , or return value optimization (§12.8.31 of the C++11 standard). The copy constructor can be skipped for virtually any function that returns a class type. This is often closely related to the actual implementation of returning class types. (Note that you're sort of relying on this too: presumably slice returns your matrix type by value, and you don't want a copy constructor called there if it would break your aliasing.)

You'll most likely need to implement this in some other way—for example, slice returning some kind of proxy type that supports the same operations and can convert to your normal matrix type, breaking aliasing during that conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM