面试题答案
一键面试以下是MyClass
类及相应成员函数的实现示例(以C++为例):
#include <iostream>
#include <stdexcept>
class MyClass {
private:
int* arr;
size_t size;
public:
MyClass(size_t s) : size(s) {
arr = new int[size];
}
~MyClass() {
delete[] arr;
}
// 拷贝构造函数
MyClass(const MyClass& other) : size(other.size) {
arr = new int[size];
for (size_t i = 0; i < size; ++i) {
arr[i] = other.arr[i];
}
}
// 赋值运算符重载
MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] arr;
size = other.size;
arr = new int[size];
for (size_t i = 0; i < size; ++i) {
arr[i] = other.arr[i];
}
}
return *this;
}
// 返回特定位置元素的引用
int& getElementRef(size_t index) {
if (index >= size) {
throw std::out_of_range("Index out of range");
}
return arr[index];
}
};
在类的场景下返回引用需要注意的方面:
- 对象生命周期:确保返回引用的对象在调用者使用该引用期间仍然有效。如果对象是局部对象(例如函数内创建的临时对象),当函数返回时该对象将被销毁,此时返回其引用会导致悬空引用,这是非常危险的。
- 内存管理:如果类涉及动态内存分配(如上述示例中的
arr
数组),需要正确实现拷贝构造函数、赋值运算符重载和析构函数,以避免内存泄漏和浅拷贝问题。否则,当对象被复制或销毁时,可能会错误地释放或重复释放内存。 - 边界检查:在返回引用前,最好对索引或其他可能影响引用对象有效性的条件进行边界检查。如上述示例中对
index
进行检查,防止越界访问。 - 多线程环境:在多线程环境下,需要注意返回引用的对象可能会被其他线程修改。可能需要使用同步机制(如互斥锁)来确保数据的一致性和线程安全。