Talk:Generic swap: Difference between revisions

→‎C++: tested
m (→‎C++: I typed it at midnight...lay off...)
(→‎C++: tested)
Line 26:
 
Would the C++ example here assume that there is a copy constructor for T types? Would it be better to have "tmp = left" rather than "tmp(left)"? --[[User:mwn3d|mwn3d]] 00:08, 14 November 2007
: Well, in some circumstances (assigning a char to a CString in Windows MFC, for example), you ''have'' to use the explicit constructor, due to the way a class was defined. Granted, it would be a poor class implementation that required explicit use of its own copy constructor, but it's not impossible.
:
: In addition, I tried a couple small programs to test the problem:
<pre>#include <iostream>
 
using namespace std;
 
int main()
{
int a = 7;
int b = int(a);
cout << b << endl;
}
</pre>
 
: This outputs "7".
:
: I also tried creating a class with no defined copy constructor:
<pre>#include <iostream>
 
using namespace std;
 
class CNoCopy
{
public:
int m_value;
CNoCopy()
{
cout << "Constructor Called" << endl;
}
 
~CNoCopy()
{
cout << "Destructor called" << endl;
}
 
void setValue( int newVal )
{
m_value = newVal;
}
 
int getValue()
{
return m_value;
}
};
 
int main()
{
CNoCopy o1;
o1.setValue( 7 );
CNoCopy o2 = CNoCopy( o1 );
cout << o2.getValue() << endl;
}
</pre>
:This outputs
<pre>Constructor Called
7
Destructor called
Destructor called
</pre>
: So the copy went ahead, without calling any explicitly-define constructor. For reference, I'm using [[G++]] 4.1.3. In all, I think the implementation is fine. --[[User:Short Circuit|Short Circuit]] 19:06, 14 November 2007 (MST)