Shallow copy, no copy constructor
没有copy constructor, second
指向的memory内容改变影响string = 'Lei'
:
#include <iostream>
#include <string>
class String {
private:
char* m_buffer;
unsigned int m_size;
public:
String(const char* string) {
m_size = strlen(string);
m_buffer = new char[m_size];
memcpy(m_buffer, string, m_size);
m_buffer[m_size] = 0;
}
~String(){
delete[] m_buffer;
}
// override [] for customized String
char& operator[](unsigned int index) {
return m_buffer[index];
}
// friend: so m_buffer can be accessed
friend std::ostream& operator<<(std::ostream& stream, const String& string);
};
std::ostream& operator<<(std::ostream& stream, const String& string){
stream << string.m_buffer;
return stream;
}
int main() {
String string = "Lei";
String second = string;
second[1] = 'a';
std::cout << string << std::endl; // Lai
std::cout << second << std::endl; // Lai
std::cin.get();
}
Deep copy, w. copy constructor
#include <iostream>
#include <string>
class String {
private:
char* m_buffer;
unsigned int m_size;
public:
String(const char* string) {
m_size = strlen(string);
m_buffer = new char[m_size];
memcpy(m_buffer, string, m_size);
m_buffer[m_size] = 0;
}
// copy constructor
String(const String& other) : m_size(other.m_size)
{
m_buffer = new char [m_size];
memcpy(m_buffer, other.m_buffer, m_size);
}
~String(){
delete[] m_buffer;
}
char& operator[](unsigned int index) {
return m_buffer[index];
}
friend std::ostream& operator<<(std::ostream& stream, const String& string);
};
std::ostream& operator<<(std::ostream& stream, const String& string){
stream << string.m_buffer;
return stream;
}
int main() {
String string = "Lei";
String second = string;
second[1] = 'a';
std::cout << string << std::endl; // Lei
std::cout << second << std::endl; // Lai
std::cin.get();
注意其中的
// copy constructor
String(const String& other) : m_size(other.m_size)
{
m_buffer = new char [m_size];
memcpy(m_buffer, other.m_buffer, m_size);
}
<=>
// copy constructor
String(const String& other) : m_size(other.m_size)
{
memcpy(this, &other, sizeof(String));
}
Tip:
- reference: still that object, use
.
- pointer: use
->