我正在为C ++中的共享指针编写一个访问器方法,如下所示:
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
因此,为了支持getBar()
的常数,返回类型应该是一个boost::shared_ptr
,它可以防止修改它指向的Bar
。我的猜测是shared_ptr<const Bar>
是我想要返回的类型,而const shared_ptr<Bar>
会阻止指针本身的重新分配指向不同的Bar
但允许修改它指向的Bar
...但是,我不是当然。我很感激,如果有人确切知道可以证实这一点,或者如果我弄错了就纠正我。谢谢!
你是对的。 shared_ptr<const T> p;
类似于const T * p;
(或者,相当于T const * p;
),也就是说,尖头物体是const
而const shared_ptr<T> p;
类似于T* const p;
,这意味着p
是const
。综上所述:
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_ptr
和unique_ptr
。
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。
#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;
}
我想基于@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
}