`const shared_ptr의 차이점`및`shared_ptr`?
다음과 같은 C ++의 공유 포인터에 대한 접근 자 메서드를 작성하고 있습니다.
class Foo {
public:
return_type getBar() const {
return m_bar;
}
private:
boost::shared_ptr<Bar> m_bar;
}
따라서 getBar()반환 유형 의 const-ness를 지원 boost::shared_ptr하려면 Barit이 가리키는 수정을 방지 해야합니다 . 내 생각 엔 그것이 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공유 포인터를 통한 객체 수정을 방지 합니다. 반환 값으로 const in boost::shared_ptr<Bar> const은 반환 된 임시 에서 상수 가 아닌 함수를 호출 할 수 없음 을 의미합니다. 실제 포인터 (예 Bar* const:) 인 경우 완전히 무시됩니다.
일반적으로 여기에서도 일반적인 규칙이 적용됩니다. const앞에 오는 것을 수정합니다. in boost::shared_ptr<Bar const>, the 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;
}
I would like to a simple demostration based on @Cassio Neri's answer:
#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
}
'developer tip' 카테고리의 다른 글
| 괄호, 점, 중괄호, = (함수) 등을 생략 할 수있는 정확한 규칙은 무엇입니까? (0) | 2020.08.19 |
|---|---|
| 함수 호출에서 "값으로 사용" (0) | 2020.08.19 |
| onclick 값에서 'javascript'대신 다른 단어를 사용할 때 브라우저에서 오류가 발생하지 않는 이유는 무엇입니까? (0) | 2020.08.19 |
| / usr / libexec / java_home에서 반환 된 Mac OS의 기본 Java VM을 어떻게 변경할 수 있습니까? (0) | 2020.08.19 |
| Angularjs는 모범 사례 축소 (0) | 2020.08.19 |