03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.6. AUTOMATICALLY GENERATED OPERATORS 77<br />

{}<br />

//...<br />

varn(that.varn)<br />

∼my class()<br />

{<br />

varn.∼typen();<br />

// ...<br />

var2.∼type2();<br />

var1.∼type1();<br />

}<br />

my class& operator=(const my class& that)<br />

{<br />

var1= that.var1;<br />

var2= that.var2;<br />

// ...<br />

varn= that.varn;<br />

return ∗this;<br />

}<br />

private:<br />

type1 var1;<br />

type2 var2;<br />

// ...<br />

typen varn;<br />

};<br />

The generation is straight <strong>for</strong>ward. The four operators are respectively called on each member<br />

variable. The careful reader has realized that the constructors and the assignment is per<strong>for</strong>med<br />

in the exact order as the variables are defined. The destructors are called in reverse order.<br />

The generation of these operators will be disabled if you define your own. The rules <strong>for</strong> this<br />

are quite simple. The simplest is <strong>for</strong> the destructor: either you define it or the compiler does.<br />

There is only one destructor (because it has no arguments). The default constructor generation<br />

is disabled when any constructor is defined by the user — even a private constructor.<br />

The copy constructor and copy assignment operator are generated automatically unless there<br />

is a user-defined version <strong>for</strong> the class type or a reference of it. In detail, if the user defines one<br />

or two of the following:<br />

• return type operator=(my class that);<br />

• return type operator=(const my class& that); or<br />

• return type operator=(my class& that);<br />

Then the compiler does not generated it. Typically, one defines only the second operator<br />

because the first one causes an extra copy 7 and the last one requires mutability what is usually<br />

not necessary <strong>for</strong> the assignment. The copy constructor can only be defined <strong>for</strong> references<br />

because it need itself <strong>for</strong> passing a value as argument. Defining a constructor or assignment <strong>for</strong><br />

any other type does not disable the generation of the copy operators.<br />

7 An exception is user-defined move semantics. 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!