`const shared_ptr <t>`和`shared_ptr <const t =“”>`?</const> </t>之间的区别

时间:2013-07-22 17:05:23

标签: c++ boost const shared-ptr

我在C ++中为共享指针编写一个访问器方法,如下所示:

class Foo {
public:
    return_type getBar() const {
        return m_bar;
    }

private:
    boost::shared_ptr<Bar> m_bar;
}

因此,为了支持getBar()的常量,返回类型应为boost::shared_ptr,以防止修改它指向的Bar。我的 guess shared_ptr<const Bar>是我想要返回的类型,而const shared_ptr<Bar>会阻止指针本身的重新分配以指向不同的Bar但允许修改它指向的Bar ......但是,我不确定。如果有人确定可以证实这一点,或者如果我弄错了就纠正我,我会很感激。谢谢!

4 个答案:

答案 0 :(得分:134)

你是对的。 shared_ptr<const T> p;类似于const T * p;(或等效地,T const * p;),即指向的对象为const,而const shared_ptr<T> p;类似于T* const p; }表示pconst。总结:

shared_ptr<T> p;             ---> T * p;                                    : nothing is const
const shared_ptr<T> p;       ---> T * const p;                              : p is const
shared_ptr<const T> p;       ---> const T * p;       <=> T const * p;       : *p is const
const shared_ptr<const T> p; ---> const T * const p; <=> T const * const p; : p and *p are const.

同样适用于weak_ptrunique_ptr

答案 1 :(得分:2)

boost::shared_ptr<Bar const>阻止修改 Bar通过共享指针对象。作为回报值, boost::shared_ptr<Bar> const中的const意味着你不能 在返回的临时函上调用非const函数;如果是的话 对于真正的指针(例如Bar* const),它将是完全的 忽略。

通常,即使在这里,通常的规则也适用:const修改 先于它:在boost::shared_ptr<Bar const>Bar; 在boost::shared_ptr<Bar> const中,它是实例化( 表达式boost::shared_ptr<Bar>是const。

答案 2 :(得分:1)

#Check this simple code to understand... copy-paste the below code to check on any c++11 compiler

#include <memory>
using namespace std;

class A {
    public:
        int a = 5;
};

shared_ptr<A> f1() {
    const shared_ptr<A> sA(new A);
    shared_ptr<A> sA2(new A);
    sA = sA2; // compile-error
    return sA;
}

shared_ptr<A> f2() {
    shared_ptr<const A> sA(new A);
    sA->a = 4; // compile-error
    return sA;
}

int main(int argc, char** argv) {
    f1();
    f2();
    return 0;
}

答案 3 :(得分:0)

我想基于@Cassio Neri的答案进行简单演示:

#include <memory>

int main(){
    std::shared_ptr<int> i = std::make_shared<int>(1);
    std::shared_ptr<int const> ci;

    // i = ci; // compile error
    ci = i;
    std::cout << *i << "\t" << *ci << std::endl; // both will be 1

    *i = 2;
    std::cout << *i << "\t" << *ci << std::endl; // both will be 2

    i = std::make_shared<int>(3);
    std::cout << *i << "\t" << *ci << std::endl; // only *i has changed

    // *ci = 20; // compile error
    ci = std::make_shared<int>(5);
    std::cout << *i << "\t" << *ci << std::endl; // only *ci has changed

}