C++ Virtual Destruction and String to Integer Conversion
1) Consider the following classes:
#include <memory>
struct Base {virtual void f();
};
struct Derived : Base {};
void f() {std::unique_ptr<Base> b = std::make_unique<Derived>();
}
void f() {Base* b = new Derived();
// ...
delete b;
}
int main() {f();
return 0;
}
2) Implement a function to convert a string to a number.
// function to convert string to a number
// 32 signed integer with sign
int convert(std::string str) {
int num = 0;
return num;
}
int main() {
// Given string of number
char s[] = "-123";
int str2num = convert(s);
std::cout << "number -" << str2num << std::endl;
return 0;
}
What is wrong with the first snippet, and how would you correctly implement the string-to-integer conversion in the second snippet?
这道题其实包含两个常见的 C++ 面试点:第一部分考察多态对象的析构行为,`Base*` 指向 `Derived` 时如果基类没有虚析构函数,直接 `delete b` 会导致派生类资源无法被正确释放;而 `std::unique_ptr<Base>` 配合虚析构则能安全管理基类指针指向派生对象。第二部分是字符串转整数,需要正确处理正负号、逐位累加、非法字符以及可能的溢出问题,常见做法是先判断符号位,再遍历字符并按十进制构造结果,必要时在边界处做 `INT_MAX/INT_MIN` 检查。