char* data 指向堆內存,負責釋放if (this == &other) return *this;ostream& operator<<(ostream&, const String&)
#include <cstring>
#include <iostream>
class String {
public:
// 普通構造
String(const char *str = nullptr) {
if (str == nullptr) {
data = new char[1];
*data = '\0';
} else {
size_t len = std::strlen(str);
data = new char[len + 1];
std::strcpy(data, str);
}
}
// 拷貝構造
String(const String &other) {
size_t len = std::strlen(other.data);
data = new char[len + 1];
std::strcpy(data, other.data);
}
// 移動構造 (C++11)
String(String && other) noexcept : data(other.data) {
other.data = nullptr;
}
// 析構
~String() {
delete[] data;
}
// 拷貝賦值 (Copy-and-swap 惯用法)
String& operator=(String other) { // 參數按值傳遞,自動調用拷貝/移動構造
std::swap(data, other.data);
return *this;
}
// 移動賦值 (C++11)
String& operator=(String && other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
other.data = nullptr;
}
return *this;
}
// 友元輸出
friend std::ostream& operator<<(std::ostream& os, const String& s) {
return os << s.data;
}
// 訪問器
const char* c_str() const { return data; }
size_t length() const { return std::strlen(data); }
private:
char *data;
};
int main() {
String s1("hello");
String s2 = s1; // 拷貝構造
String s3;
s3 = s1; // 拷貝賦值
String s4 = std::move(s1); // 移動構造
s3 = std::move(s2); // 移動賦值
std::cout << s3 << std::endl;
return 0;
}
String& operator=(String other) 參數按值傳遞,編譯器自動選擇拷貝或移動構造。函數體內 swap 交換資源,舊資源隨 other 析構釋放。優勢:
轉移所有權而非複製,noexcept 保證不拋出異常,使 STL 容器重新分配時優先使用移動操作,大幅提升性能。
std::string/std::vector/std::unique_ptr 等 RAII 類型,避免手寫資源管理const 正確性(如 c_str() 應為 const 方法)手寫 String 是理解 C++ 資源管理、拷貝控制、移動語義、異常安全的最佳練習。實際項目中請直接使用 std::string。