![](/img/trans.png)
[英]Is returning a raw pointer instead of unique_ptr good coding practice?
[英]Is this a good practice to rename and reinclude std::unique_ptr?
代碼如下
// in ptr.h
#pragma once
#include <memory>
template<class T> using Ptr = std::unique_ptr<T>;
因此,每次我使用std :: unique_ptr時,都會包含“ ptr.h”並將其用作Ptr。 這是一個好習慣嗎?
這種事情只會損害可讀性。 一般的C ++程序員在知道您對Ptr
理解是什么之前,會先知道unique_ptr
是什么的幾率更高。 而且我可以谷歌搜索前者而不是后者。
假設您的要求已更改,並決定使用std::share_ptr
。 您自然會這樣做:
template<class T> using Ptr = std::shared_ptr<T>;
好! 大! 使用Ptr
的代碼沒有任何變化。 但是std::shared_ptr
在語義上與std::unique_ptr
不同。 當一些不知道更改的不知情的程序員繼續認為Ptr
仍然是std::unique_ptr
... kaboom!
我了解到的一件事是,重要的是不要為了簡短而犧牲代碼的可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.