简体   繁体   English

带指针的顶级const

[英]top-level const with pointers

Suppose that I have class which has std::vector<Object*> 假设我有一个带有std::vector<Object*>

Should method like: 应该这样的方法:

const std::vector<Object*> getSth() const
{
    return class_member_vector;
}

be converted to: 转换为:

std::vector<Object*> getSth() const
{
    return class_member_vector;
}

It is always safe and should be always corrected in that way? 它始终是安全的,应该始终以这种方式进行纠正?

Yes, you should use the second variant for clarity. 是的,为清晰起见,您应该使用第二种变体。 And yes, this is always safe. 是的,这始终是安全的。 In both variants you are returning the return value by value , so the class cannot be affected by modifying the returned vector. 在这两种变体中,您都按值返回返回值,因此,修改返回的向量不会影响该类。 Also in both cases the callee can modify the objects pointed to by the vector elements, so the outer const does not make a difference there either. 同样在这两种情况下,被调用方都可以修改向量元素指向的对象,因此外部const也不会在其中起作用。

The const in the first variant is misleading and should be removed. 第一个变体中的const具有误导性,应将其删除。

But you may want to consider to return a const std::vector<Object*>& reference for performance reasons. 但是出于性能原因,您可能需要考虑返回const std::vector<Object*>&引用。 It depends on your use model of the class (eg lifetime, scope) whether this is a good idea or not. 这是否一个好主意取决于类的使用模型(例如,生存期,范围)。 Performance wise it is a good idea to return by const reference since all STL containers make deep-copies which are rather costly. 在性能方面,通过const引用返回是个好主意,因为所有STL容器都会进行深层复制,而这是相当昂贵的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM