求教个 C++ Get 函数怎么写的问题

查看 37|回复 2
作者:Betsy   
代码
#include[i]
#include
#include [u]
enum struct Status {
    kOk = 0,
};
struct Student {
    std::string name;
    std::size_t age;
};
class Table {
   public:
    Table() {
        this->map_.insert(std::make_pair("w1", Student("li", 23)));
        this->map_.insert(std::make_pair("s2", Student("zhao", 18)));
    }
    Status Get(const std::string& key, Student* value) {
        *value = this->map_[key];
        return Status::kOk;
    }
    Student Get(const std::string& key) { return this->map_[key]; }
   private:
    std::unordered_map map_;
};
int main(int argc, char* argv[]) {
    Table table;
    Student stu1;
    const Status& status = table.Get("w1", &stu1);
    std::cout
结果
li:23
zhao:18
问题
1. Status Get(const std::string& key, Student* value);
2. Student Get(const std::string& key);
在 Java/Python 等语言中,个人更喜欢第 2 种写法;但是 C++ 中,一些项目更倾向于第 1 种写法,为啥呢?这样有什么好处吗?
fgwmlhdkkkw   
c++的逻辑上“谁申请的谁释放”。
sagaxu   
两个区别,一个是内存管理,一个是错误码。
Java/Python 没有那么细致的内存管理,比如 C++中,可以栈上分配 Student ,并且复用
您需要登录后才可以回帖 登录 | 立即注册

返回顶部