Copy constructor

Hi guys quick question on copy constructors.

Lets Say there is a Vector class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Vector
{
public:
	Vector(int capacity) : m_capacity(capacity), m_Size(0)
	{
		T * temp = nullptr;
		try
		{
			temp = new T[m_capacity];
		}
		catch (std::bad_alloc& e)
		{
			std::cout << e.what();
		}

		m_Array = temp;
	}

	~Vector()
	{
		delete[] m_Array; // would I try and catch here ??
	}

	const Vector operator=(const Vector & v)
	{
		if (this == &v)
		{
			return *this;
		}

		m_Size = v.m_Size;
		m_capacity = v.m_capacity;


		T * temp = new T[v.m_capacity];

		if (temp)
		{
			memcpy(temp, v.m_Array, sizeof(m_Array[0]) * m_capacity);
		}

		delete[] m_Array; // make sure your copy ctr initialises m_Array with NULL you can delete a null but not an uninitialised pointer
		m_Array = temp;
	}


/////////////////////CPY CTR HERE
	Vector(const Vector<T> & V) : m_Array(nullptr)
	{
		operator=(V); // Access violation here
	}
	
}




And I wanted to create a copy ctr so when passed into function e.g

1
2
3
4
5
6
7
8
9
10
11
template <typename T>
void f00(Vector<T> V) // this will trigger a copy ctr which should be defaulted 
{

	for (auto it = V.begin(); it != V.end(); it++)
	{
		std::cout << *it << std::endl;

	}

}


it will deep copy the vector, I understand that it should be passed by reference but out of curiosity why is it giving me an access violation error in the copy ctr?
> Access violation
that's a runtime error, I cannot even compile your code.
Provide enough code to reproduce your issue.


By the way
1
2
3
4
5
6
7
8
9
10
11
//line 7
try
{
	temp = new T[m_capacity];
}
catch (std::bad_alloc& e)
   //...

//line 35
T * temp = new T[v.m_capacity];
	if (temp)
decide yourself, ¿new[] returns a null pointer or it throws an exception in case of failure?
A few things:

a) shouldn't use 'this' inside a constructor
b) operator = should return a reference to self (and this should be why you're crashing!)

Topic archived. No new replies allowed.