简体   繁体   中英

Why doesn't common c++ compiler optimize away object copy?

I have the source below:

#include <iostream>
struct A{
    int data[10000]; // A large data field
    void print() const{
        for(int i=0;i<100;i++){
            std::cout<<data[i]<<",";
        }
        std::cout<<std::endl;
    }
};
struct B{
    A data;
    void print() const{
        for(int i=0;i<100;i++){
            std::cout<<data.data[i]<<" ";
        }
        std::cout<<std::endl;
    }
};


int main(){
    A a;
    a.data[50]=10;
    a.data[60]=5;
    a.data[70]=3;
    a.print();
    B b{a};
    b.print();          
}

It holds a large data field in A, puts it into B and then executes its member function. Now, since B does not have any other data field than A, I think the compiler could actually optimize away the copy and just reuse the same data block, executing different member functions. However, according to https://godbolt.org/g/21z7TT , neither the latest version of g++ nor clang with -O3 compile option optimizes the memcpy away. Is there a reason why this code cannot be optimized, and is there a way to let the compiler optimize it?

It doesn't optimize away the copy because you have literally instructed it to make a copy. struct B { A data; ... }; says that B contains its own copy of an A structure.

In this particular minature program, a compiler could theoretically use the same memory without consequence. However, that ability goes away if any of a number of things change:

  • a is used again
  • B contains any data members other than A
  • b is passed to another function
  • others I haven't thought of.

Given how rare the conditions for this optimization are, I'm not surprised there is no special compiler case for it.

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