unique_ptr 부스트 상당?
부스트 라이브러리에 C ++ 1x의 std :: unique_ptr에 해당하는 클래스가 있습니까? 내가 찾고있는 동작은 예외 안전 팩토리 기능을 가질 수 있다는 것입니다.
std::unique_ptr<Base> create_base()
{
return std::unique_ptr<Base>(new Derived);
}
void some_other_function()
{
std::unique_ptr<Base> b = create_base();
// Do some stuff with b that may or may not throw an exception...
// Now b is destructed automagically.
}
편집 : 지금, 나는이 시점에서 얻을 수있는 최선의 것처럼 보이는이 해킹을 사용하고 있습니다 ...
Base* create_base()
{
return new Derived;
}
void some_other_function()
{
boost::scoped_ptr<Base> b = create_base();
// Do some stuff with b that may or may not throw an exception...
// Now b is deleted automagically.
}
unique_ptrC ++ 0x (표준 라이브러리의 일부이므로 Boost가 제공 할 필요가없는 경우) 없이는 만들 수 없습니다.
특히 C ++ 0x의 기능인 rvalue 참조 unique_ptr가 없으면 Boost를 사용하거나 사용하지 않고 강력한 구현 이 불가능합니다.
C ++ 03에는 각각 결함이 있지만 몇 가지 가능한 대안이 있습니다.
boost::shared_ptr아마도 기능 측면에서 가장 간단한 대체품 일 것입니다. 다른 방법으로 사용unique_ptr하고 작동 하는 곳이면 어디에서나 안전하게 사용할 수 있습니다 . 참조 계산이 추가 되었기 때문에 효율성이 떨어집니다. 그러나 모든 것을 처리 할 수있는 간단한 드롭 인 교체를 찾고 있다면unique_ptr이것이 최선의 방법 일 것입니다. (물론, ashared_ptr는 훨씬 더 많은 일을 할 수 있지만 단순히을 (를)위한 드롭 인 대체물로 사용할 수도 있습니다unique_ptr.)boost::scoped_ptr유사unique_ptr하지만 소유권 이전을 허용하지 않습니다. 스마트 포인터가 평생 동안 독점 소유권을 유지하는 한 훌륭하게 작동합니다.std::auto_ptr와 매우 유사하게 작동unique_ptr하지만 몇 가지 제한이 있습니다. 주로 표준 라이브러리 컨테이너에 저장할 수 없습니다. 소유권 이전을 허용하는 포인터를 찾고 있지만 컨테이너에 저장하거나 복사 할 수는없는 경우, 이것은 아마도 좋은 방법 일 것입니다.
Boost 1.57 부터 Boost.Move 라이브러리에 공식 unique_ptr구현이 있습니다.
로부터 문서 :
(...) std :: unique_ptr의 드롭 인 대체품으로 C ++ 03 컴파일러에서도 사용할 수 있습니다.
코드는 <boost/move/unique_ptr.hpp>헤더 파일 에서 사용할 수 있으며 boost::movelib네임 스페이스에 있습니다. 또한 Boost.Move 라이브러리는 네임 스페이스 에서도에서 make_unique()팩토리 기능을 제공 합니다.<boost/move/make_unique.hpp>boost::movelib
따라서 질문의 예는 다음과 같이 구현 될 수 있습니다.
#include <boost/move/unique_ptr.hpp>
using boost::movelib::unique_ptr;
unique_ptr<Base> create_base()
{
return unique_ptr<Base>(new Derived);
}
Wandbox에서 라이브 예제를 참조하십시오 . 코드는 C ++ 98 모드 (!)에서 gcc 4.6.4로 잘 컴파일됩니다.
boost::movelib::unique_ptr기본 / 파생 클래스가 있는 경우에 적용 할 때 흥미로운 점 은 구현에서 기본 클래스의 가상 소멸자 선언에 대한 컴파일 시간 검사를 제공한다는 것입니다. 생략 하면 코드가 컴파일되지 않습니다 (컴파일러 오류 메시지를 보려면 "실행 (...)"버튼을 클릭하십시오).
한 가지 사소한 문제는 boost/move디렉토리 에서 오는 것을 포함 하지만 코드가 boost::movelib네임 스페이스에 있다는 것입니다 (미묘한 차이가 있지만 성 가실 수 있음).
자세한 내용은 boost 메일 링 목록에 대한 스레드 를 참조하십시오.
Thanks to Ion Gaztañaga for this absolutely unique and useful piece of code.
You might want to try Howard Hinnant's 'proof of concept' unique_ptr<> implementation for C++03 (disclaimer - I haven't):
One of his examples is returning a unique_ptr<int>:
unique_ptr<int> factory(int i)
{
return unique_ptr<int>(new int(i));
}
How about unique_ptr from the interprocess library?
I've used Howard Hinnant's unique_ptr. If you are not really good at reading crazy metaprogramming errors from you compiler you might want to steer clear. It however does act just like a unique_ptr in 90% of the cases.
Otherwise I'd suggest passing paramters as boost::scoped_ptr& and swap internally to steal ownership. To get unique_ptr style return values use an auto_ptr. Capture the auto_ptr return value in a shared_ptr or scoped_ptr to avoid using the auto_ptr directly.
ReferenceURL : https://stackoverflow.com/questions/2953530/unique-ptr-boost-equivalent
'Program Club' 카테고리의 다른 글
| .htm 또는 .html 확장자-어느 것이 정확하고 다른 것은 무엇입니까? (0) | 2021.01.06 |
|---|---|
| 설정 앱을 열지 않아도 Settings.bundle의 설정을 기본값으로 할 수 있습니까? (0) | 2021.01.06 |
| Java 프리미티브는 스택 또는 힙으로 이동합니까? (0) | 2021.01.06 |
| vs. font-weight : bold & (0) | 2021.01.06 |
| 테이블 레이아웃에 동적으로 행을 추가하는 방법 (0) | 2021.01.06 |