先说说程序员(应届生)面试的一般过程,一轮面试(面对一到两个面试官)一般是四、五十分钟,面试官会问两三个编程问题(通常是两大一小),因此留给每个编程题的时间只有 20 分钟。这 20 分钟不光是写代码,还要跟面试官讨论你的答案并解答提问,比如面试官拿过你的答案纸,问某一行代码如果修改会有什么后果。因此真正留给在纸上或白板上写代码的时间也就 10 分钟上下。本文给出了一个能用 10 分钟时间在纸上写出来且不会有错的 String class,强调正确性及易实现(白板上写也不会错),不强调效率与功能完备。
#include #include // A trivial String class that designed for write-on-paper in an interviewclass String{ public: String()
: data_(new char ) {
*data_ = '\0'; } String(const char* str)
: data_(new char[strlen(str) + 1]) {
strcpy(data_, str); } String(const String& rhs)
: data_(new char[rhs.size() + 1]) {
strcpy(data_, rhs.c_str()); } /* Implement copy-ctor with delegating constructor in C++11 String(const String& rhs)
: String(rhs.data_) { } */ ~String() noexcept {
delete[] data_; } /* Traditional: String& operator=(const String& rhs) {
String tmp(rhs);
swap(tmp);
return *this; } */ // In C++11, this is unifying assignment operator String& operator=(String rhs) // yes, pass-by-value {
// http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap
swap(rhs);
return *this; } // C++11 move-ctor String(String&& rhs) noexcept
: data_(rhs.data_) {
rhs.data_ = nullptr; } /* Not needed if we have pass-by-value operator=() above,
* and it conflits. http://stackoverflow.com/questions/17961719/ String& operator=(String&& rhs) {
swap(rhs);
return *this; } */ // Accessors size_t size() const {
return strlen(data_); } const char* c_str() const {
return data_; } void swap(String& rhs) {
std::swap(data_, rhs.data_); } private: char* data_;};
=() above, * and it conflits. http://stackoverflow.com/questions/17961719/ String& operator=(String&& rhs) { swap(rhs); return *this; } */ // Accessors size_t size() const { return strlen(data_);
}
const char* c_str() const { return data_;
}
void swap(String& rhs) { std::swap(data_, rhs.data_);
}
private: char* data_;};