返回对对象向量的 const 引用
我有两个与同一问题相关的问题:
如何返回对属于某个类的向量的引用?
我有这门课:
类系统{ 受保护: 矢量
s; 民众: 系统(); 矢量 & getS() {return s;} //(1) }; (1) 应返回向量
<前><代码>主(){ sys* my_sys = 新的 sys(); 矢量s
的引用。但是,在main()
中:&t1 = my_sys->getS(); //(2) 矢量 t2 = my_sys->getS(); //(3) ... } t1
是对s
的引用(即,当t1
更改时,my_sys.s
也会更改)。t2
是s
的副本(即,当t2
更改时,my_sys.s 不会更改)。
为什么第 (3) 行有效?
我不希望在类之外更改
my_sys.s
,但出于效率考虑,我想返回一个引用。我应该把const
放在哪里?我尝试将第 (1) 行更改为
const vector
& getS() {return s;} //(4) 但我不确定这是否足够。
I have 2 questions related to the same problem:
How can I return a reference to a vector which belongs to a class?
I have this class:
class sys{ protected: vector<int> s; public: sys(); vector<int>& getS() {return s;} //(1) };
(1) should return the reference of the vector
s
. However, inmain()
:main(){ sys* my_sys = new sys(); vector<int> &t1 = my_sys->getS(); //(2) vector<int> t2 = my_sys->getS(); //(3) ... }
t1
is a reference tos
(i.e. whent1
is changedmy_sys.s
is changed as well).t2
is a COPY ofs
(i.e. whent2
is changed my_sys.s is NOT changed).
Why does line (3) work?
I do not want it to be possible to change
my_sys.s
outside of the class, but I want to return a reference because of efficiency. Where do I put theconst
?I tried to change line (1) to
const vector<int>& getS() {return s;} //(4)
but I am not sure if that is enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第 3 行之所以有效,是因为 t2 是从 getS() 返回的引用复制构造的。
对 getS() 返回的引用进行 const 限定的方式是可以的。您也可以对 getS() 进行 const 限定,即:
以便可以在 const sys 上调用 getS()。
Line 3 works because t2 is copy-constructed from the reference returned by getS()
The way you const-qualify the reference returned by getS() is OK. You could const-qualify getS() as well, i.e.:
so that getS() could be called on a const sys.
第 3 行之所以有效,是因为 c++ 调用向量上的复制构造函数。
您的函数返回一个引用,该引用被传递给向量复制构造函数,并构造您的变量 t2 。
这是允许的,因为向量的复制构造函数未定义为显式。
您无法使用通用类型来防范这种情况。
在您自己的类中,您可以将复制构造函数标记为显式,并且赋值将失败。
您可以返回一个 const 指针。
这可以防止复制 - 但可能很危险,因为用户可能期望能够将指针传递到其有效范围之外。
Line 3 works because c++ calls the copy constructor on the vector.
Your function returns a reference, that reference is passed to the vector copy constructor and your variable t2 is constructed.
This is allowed as the copy constructor of vector is not defined as explicit.
You cannot guard against this with a general type.
In your own class you can mark the copy constructor explicit and the assignment would fail.
You could return a const pointer instead.
This would guard against the copy - but might be dangerous as users may expect to be able to pass the pointer beyond its valid scope.
第 (3) 行
对于 int 类型,复制很简单。如果你把对象放在那里并且它们有一个复制CTor,这也将起作用。
第 (4)
行将
函数也声明为 const。
并这样称呼它
Line (3)
For the int type it is trivial to copy. If you put objects in there and they have a Copy CTor, this will also work.
Line (4)
Make it
so the function is also declared as const.
And call it like this