An empty class, the compiler defaults to generating constructors, copying constructors, assigning functions, destructors, and a class. If you override the copy constructor, you must customize a constructor. The following code compiles an error: Error C2512: "B": no suitable default constructor available
Class B
{public
:
B (const b &b)
{
}
};
int main (void)
{
b b;
GetChar ();
return 0;
}
Amended to:
Class B
{public
:
B () {}
B (const b &b)
{
}
};
int main (void)
{
b b;
GetChar ();
return 0;
}
Correct spelling of copy constructors and assignment functions (if (this!= &b))
Class B
{public
:
B (int v)
{
m_value = v;
}
B (const b &b)
{
m_value = b.m_value;
}
b &operator = (const b &b)
{
if (this!= &b)
{
m_value = b.m_value;
}
return *this;
}
Private:
int m_value;
};
When a function returns a value as an object, consider the efficiency of the return statement.
b createObj0 (void)
{return
B (0);
}
b createObj1 (void)
{b
b (0);
return b;
}
CreateObj0 creates a temporary object and returns it, the compiler creates and initializes the temporary object directly in the external storage unit, eliminating the process of copying and destructor. CreateObj1 creates a B object, and then copies the construct to copy B to the external storage unit, and then the B object is also destructor. Compare the following two groups of code with the results of your operation:
#include <stdio.h>
int g_counter = 0;
Class B
{public
:
b (void)
{
m_value = g_counter++;
printf ("B () m_value=%d\n", m_value);
}
~b ()
{
printf ("~b () m_value=%d\n", m_value);
}
B (const b &a)
{
m_value = g_counter++;
printf ("B (const b &a) m_value=%d\n", m_value);
}
b &operator= (const b&a)
{
printf ("B &operator= (const b&a) \ n");
return *this;
}
Private:
int m_value;
};
b createObj0 (const b b)
{
b bb (b);
return BB;
}
b createObj1 (const B)
{return
B (b);
}
int main (void)
{
B __b;
B _b = createObj0 (__b);
return 0;
}
Run Result:
#include <stdio.h>
int g_counter = 0;
Class B
{public
:
b (void)
{
m_value = g_counter++;
printf ("B () m_value=%d\n", m_value);
}
~b ()
{
printf ("~b () m_value=%d\n", m_value);
}
B (const b &a)
{
m_value = g_counter++;
printf ("B (const b &a) m_value=%d\n", m_value);
}
b &operator= (const b&a)
{
printf ("B &operator= (const b&a) \ n");
return *this;
}
Private:
int m_value;
};
b createObj0 (const b b)
{
b bb (b);
return BB;
}
b createObj1 (const B)
{return
B (b);
}
int main (void)
{
B __b;
B _b = createObj1 (__b);
return 0;
}
Run Result: