sebma
June 12th, 2006, 10:27 AM
Hi ALL,
I am wandering if the copy constructor and = operator for a CLI ref class is implemented correctly below.
// ClrConsole.cpp : main project file.
#include "stdafx.h"
using namespace System;
ref class SomeRef
{
public:
SomeRef(int x, String^ name):m_X(x), m_Name(name) {}
// copy constructor
SomeRef(const SomeRef% rhs)
{
m_X = rhs.m_X;
m_Name = rhs.m_Name;
}
// assignment operator
SomeRef% operator=(const SomeRef% rhs)
{
if (this == %rhs) // prevent assignment to self
return *this;
m_X = rhs.m_X;
m_Name = rhs.m_Name;
return *this;
}
virtual String^ ToString() override
{
return (m_X.ToString() + " " + m_Name);
}
private:
int m_X;
String^ m_Name;
};
void DoSomething(SomeRef ref)
{
Console::WriteLine(L"ref {0}", ref.ToString());
}
int main(array<System::String ^> ^args)
{
SomeRef s1(99, "abc");
SomeRef^ r1 = %s1;
SomeRef s2 = *r1;
Console::WriteLine(L"sr1 {0}", s1.ToString());
Console::WriteLine(L"1 {0}", r1->ToString());
Console::WriteLine(L"sr2 {0}", s2.ToString());
SomeRef^ r2 = gcnew SomeRef(42, "xyz");
DoSomething(*r2);
SomeRef s3(64, "def");
s3 = s3; // assignment to self
Console::WriteLine(L"s3 {0}", s3.ToString());
s3 = *r2;
Console::WriteLine(L"s3 {0}", s3.ToString());
return 0;
}
I am wandering if the copy constructor and = operator for a CLI ref class is implemented correctly below.
// ClrConsole.cpp : main project file.
#include "stdafx.h"
using namespace System;
ref class SomeRef
{
public:
SomeRef(int x, String^ name):m_X(x), m_Name(name) {}
// copy constructor
SomeRef(const SomeRef% rhs)
{
m_X = rhs.m_X;
m_Name = rhs.m_Name;
}
// assignment operator
SomeRef% operator=(const SomeRef% rhs)
{
if (this == %rhs) // prevent assignment to self
return *this;
m_X = rhs.m_X;
m_Name = rhs.m_Name;
return *this;
}
virtual String^ ToString() override
{
return (m_X.ToString() + " " + m_Name);
}
private:
int m_X;
String^ m_Name;
};
void DoSomething(SomeRef ref)
{
Console::WriteLine(L"ref {0}", ref.ToString());
}
int main(array<System::String ^> ^args)
{
SomeRef s1(99, "abc");
SomeRef^ r1 = %s1;
SomeRef s2 = *r1;
Console::WriteLine(L"sr1 {0}", s1.ToString());
Console::WriteLine(L"1 {0}", r1->ToString());
Console::WriteLine(L"sr2 {0}", s2.ToString());
SomeRef^ r2 = gcnew SomeRef(42, "xyz");
DoSomething(*r2);
SomeRef s3(64, "def");
s3 = s3; // assignment to self
Console::WriteLine(L"s3 {0}", s3.ToString());
s3 = *r2;
Console::WriteLine(L"s3 {0}", s3.ToString());
return 0;
}