Copy constructors, Assignment operators, and Copy assignment operator

Posted yetanghancpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Copy constructors, Assignment operators, and Copy assignment operator相关的知识,希望对你有一定的参考价值。

 1 #include <cassert> // for assert()
 2 #include <initializer_list> // for std::initializer_list
 3 #include <iostream>
 4  
 5 class IntArray
 6 {
 7 private:
 8     int m_length;
 9     int *m_data;
10  
11 public:
12     IntArray() :
13         m_length(0), m_data(nullptr)
14     {
15     }
16  
17     IntArray(int length) :
18         m_length(length)
19     {
20         m_data = new int[length];
21     }
22  
23     IntArray(const std::initializer_list<int> &list): // allow IntArray to be initialized via list initialization
24         IntArray(list.size()) // use delegating constructor to set up initial array
25     {
26         // Now initialize our array from the list
27         printf("initializer_lis start!!!!
");
28         
29         int count = 0;
30         for (auto &element : list)
31         {
32             m_data[count] = element;
33             ++count;
34         }
35     }
36      IntArray(const IntArray &array)
37     {
38         m_length = array.m_length;
39         m_data = new int[m_length];
40         
41         int i = 0;
42         for (; i < m_length; i++)
43         {
44             m_data[i] = array.m_data[i];
45         }
46     }
47         
48     ~IntArray()
49     {
50         delete[] m_data;
51         // we don‘t need to set m_data to null or m_length to 0 here, since the object will be destroyed immediately after this function anyway
52     }
53  
54     int& operator[](int index)
55     {
56         assert(index >= 0 && index < m_length);
57         return m_data[index];
58     }
59     void operator=(const std::initializer_list<int> &list)
60     {
61         m_length = list.size();
62         m_data = new int[m_length];
63         int count = 0;
64         for (auto &element : list)
65         {
66             m_data[count] = element;
67             ++count;
68         }
69 
70     }
71     
72     void operator=(const IntArray &array)
73     {
74         m_length = array.m_length;
75         m_data = new int[m_length];
76         
77         int i = 0;
78         for (; i < m_length; i++)
79         {
80             m_data[i] = array.m_data[i];
81         }
82 
83 
84     }
85     int getLength() { return m_length; }
86 };

 

以上是关于Copy constructors, Assignment operators, and Copy assignment operator的主要内容,如果未能解决你的问题,请参考以下文章

iOS中assign,copy,retain之间的区别以及weak和strong的区别

IOS开发 strong,weak,retain,assign,copy nomatic 等的区别与作用

iOS中的assign,retain,copy等

ios OC 关键字 copy,strong,weak,assign的区别

strong ,weak,copy关键字使用,及weak跟assign区别

属性readwrite,readonly,assign,retain,copy,nonatomic