Question on move constructors

Graziano Servizi Graziano.Servizi@bo.infn.it
Mon Jan 28 16:28:00 GMT 2013


Thanks for your kind and quick answer.

Indeed now the output from sample_code agrees (except minor changes) 
with the one given.

I had to give, however, the noexcept specifier not only to the "move" 
functions, but to the copy constructor and copy assignment operator as well.


Trying the same on my own class was unsuccessful: I have a simple, 
ordinary, class, say "class my_class", with several constructors,
the copy and move constructors and the move and copy = operators.

ALL of them are NOW noexcept specified.

Nevertheless when I write

                 my_class my_object(MY_FUNCTION());

where MY_FUNCTION() is a function returning a my_class object,
neither the copy constructor nor the move constructor is called: is this 
due to RETURN VALUE OPTIMIZATION? Doesn't MY_FUNCTION() is an rvalue?

Must I "noexcept" EVERY method of my_class?

Here follows the full example I mean:

# include <iostream>
using namespace std;

class my_class
  {
   public:
   my_class()
     {
      clog << "default constructor\n";
      }
   my_class(double x, int y)
     {
      clog << "a sample constructor\n";
     }
   my_class(const my_class &o)
     {
      clog << "the copy constructor\n";
     }
   my_class(my_class &&o) noexcept
     {
      clog << "the move constructor\n";
      }
   my_class &operator = (const my_class &o)
     {
      clog << "the copy assignment operator\n";
      return * this;
     }
   my_class &operator = (my_class &&o) noexcept
     {
      clog << "the move assignment operator\n";
      return * this;
     }
   };

my_class MY_FUNCTION() // a function returning a my_class (not by reference)
   {
     my_class an_object(1.1, 0); // calls the parametric ctor
     return an_object;
    }

int main()
  {
   my_class my_object(MY_FUNCTION()); // would call the move ctor ? NO 
CTOR AT ALL IS CALLED (?)
   my_class other_object(move(MY_FUNCTION())); // this does
   }

// output from the program:
// a sample constructor
// a sample constructor
// the move constructor

// End of sample code

Thanks again.



More information about the Gcc-help mailing list