作者poyenc (发箍)
看板C_and_CPP
标题Re: [问题] vector<int>& nums 和vector<int>* vec
时间Fri Nov 30 22:14:29 2018
※ 引述《s505015 (s505015)》之铭言:
: 最近自学c++
: 跑去leetcode上面研究
: 发现到了这个问题
: vector<int>* vec 和vector<int>& num
: 照两个实在是看不懂
: 我去查了一下
: vector<int>a 那个a应该是vector名字吧
: 但是一开始我就把vector<int>* vec的* vec想成为名字
: 但是好像又不太对
: 所以感到很困惑
: 想这个好久了
: 希望有人帮忙
: 谢谢
哈罗, 看到 raw pointer 觉得惊惊的, 所以顺便推广下, 首先可
以参考 Herb Sutter 在 CppCon 2016 的 talk:
Leak-Freedom in C++... By Default.
https://youtu.be/JfmTagWcqoE
在 C++ 使用物件的时候, 必需时刻关注物件的生命周期, 物件会
经过建构, 解构等时期, 而参与这些过程与否, 语意上我们称为
owning / non-owning
(ownership). 下面就列出几个常见的使用
情境, 还有说明它们的差别:
string s;
// owning
string & rs = s;
// non-owning
string * ps = &s;
// (*) non-owning
string * ps2 =
new string;
// (*) owning
string * ps3 =
nullptr;
// (*) non-owning, optional
unique_ptr<string> ups{...};
// owning
shared_ptr<string> sps{...};
// owning, share ownership
// with others
weak_ptr<string> wps{...};
// non-owning, may request
// temporary ownership
observer_ptr<string> ops{...};
// non-owning
从上面可以发现 raw pointer 的语意上是有分别的, 但你从型别
根本无法看出它的意图, 有个最恶名昭彰的例子是 C-style 字串:
char c =
'a';
char * pc = &c;
puts(pc);
// what result?
为了消除 raw pointer 语意上的分歧, C++ Core Guidelines 提
出几个型别来帮助判断, 大部分都可以在 GSL (Guidelines
Support Library) 里找到:
char c =
'a';
owner<
char*> oc =
new char;
// owning
not_null<
char*> nnc{&c};
// non-owning, same as char&
string_view sv =
"hello";
// non-owning, for c-style string or
// char sequence not ended by '\0'
在这边简单做个总结:
1. owning 语意:
a.
不需要动态绑定对象: 使用
一般物件或
const unique_ptr / shared_ptr
b.
需要动态绑定对象: 使用 unique_ptr / shared_ptr
2. non-owning 语意:
a.
不需要动态绑定对象: 使用参考
b.
需要动态绑定对象: 使用 weak_ptr / observer_ptr
3. 非用 raw pointer 不可:
a. owning 语意: 使用 owner<T*>
b. non-owning 语意: 物件
需存在使用 not_null<T*>
物件
可不存在用 T*
参考资料:
C++ Core Guidelines
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Guidelines Support Library (Microsoft)
https://github.com/Microsoft/GSL
GSL Lite
https://github.com/martinmoene/gsl-lite
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.193.76.85
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1543587276.A.11C.html
1F:推 james732: 推好文连发 11/30 22:22
2F:推 hare1039: 推 11/30 23:48
3F:推 Serge45: 推 12/01 00:58
※ 编辑: poyenc (123.193.76.85), 12/01/2018 09:55:37
4F:推 s505015: 谢谢您 12/02 10:38