Copy constructor is not called as a result of a function

GCC prints an expression - no matter how I try to prevent it. I tried

  • -fno-inline
  • -O0
  • __attribute__ ((noinline))
  • dummy asm("")

No success! Here is the code:

 #include<iostream> using namespace std; struct A { A() {cout << "A::A()" <<endl; } A(const A& a) {cout << "A::A(copy)" <<endl; } A& operator=(const A& a) {cout << "A::=()" <<endl; return *this;} }; A __attribute__ ((noinline)) func() { cout << "func()" << endl; A loc; asm(""); return loc; } int main() { A a = func(); } 

The unfortunate conclusion of this (g ++ (Ubuntu / Linaro 4.5.2-8ubuntu4) 4.5.2)

 func() A::A() 

What happened to the statement A a = func (); ??

The reason for this experiment is that I would like to know what happens when execution arrives at this statement (because I need to control how this is done):

 A a = func(); 

I read that the copy constructor is called when executed

 A a = b; 

(In this case, the copy instance is called. But not in the case of A a = func ();) Instead, the function is built-in. I NEED controls this operator, since my "structure A" in real life contains dynamically distributed data that needs to be taken care of.

Did I miss something obvious here ?!

+6
source share
3 answers

No, this has nothing to do with the built-in function. Embedding a function would not change the observed behavior.

This is an optimization called copy elision that allows the compiler to avoid copying by creating a return value directly at the destination. You can disable it using the g ++ -fno-elide-constructors flag.

In any case, dynamically allocated data should not be a problem. Assuming the finished copy constructor will make sense, the only difference you'll see is probably higher.

+18
source

If struct A contains dynamically allocated data, then it is your responsibility to manage this memory in the appropriate destructor / constructor. Many classes manage dynamically distributed data and work well with ellipse copies. RVO and NRVO are important optimizations.

+6
source

In case someone (like me) really wants to avoid inline :

 -fkeep-inline-functions -fno-inline 

-fkeep inline functions
Even if all calls to this function are integrated and the function is declared as static, nevertheless, a separate version of the function is called that is called at run time. This switch does not affect external built-in functions.

-fno-row
Ignore the built-in keyword. Usually this option is used to prevent the compiler from expanding the built-in functions. Please note that if you do not optimize, no functions can be deployed inline.

+3
source

Source: https://habr.com/ru/post/896212/


All Articles