Programing

boost :: shared_ptr이있는 NULL 포인터?

lottogame 2021. 1. 8. 07:46
반응형

boost :: shared_ptr이있는 NULL 포인터?


다음과 같은 것은 무엇입니까?

std::vector<Foo*> vec;
vec.push_back(NULL);

다룰 때 boost::shared_ptr? 다음 코드입니까?

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());

참고 : 이러한 개체를 많이 푸시 백 할 수 있습니다. 전역 정적 nullPtr객체를 어딘가에 선언해야합니까 ? 이렇게하면 그중 하나만 구성하면됩니다.

boost::shared_ptr<Foo> nullPtr;

귀하의 제안 ( shared_ptr<T>인수없이 생성자 호출 )이 정확합니다. (값이 0 인 생성자를 호출하는 것은 동일합니다.) 두 경우 모두 (직접 생성 또는 복사 생성) 생성이 필요하기 때문에 vec.push_back()이것이 기존을 호출 하는 것보다 느리지 않을 것이라고 생각합니다 shared_ptr<T>.

그러나 "더 좋은"구문을 원하면 다음 코드를 시도해 볼 수 있습니다.

class {
public:
    template<typename T>
    operator shared_ptr<T>() { return shared_ptr<T>(); }
} nullPtr;

이것은 nullPtr다음과 같은 자연 구문을 사용 하는 단일 전역 객체를 선언 합니다.

shared_ptr<int> pi(new int(42));
shared_ptr<SomeArbitraryType> psat(new SomeArbitraryType("foonly"));

...

pi = nullPtr;
psat = nullPtr;

여러 번역 단위 (소스 파일)에서 이것을 사용하는 경우 클래스에 이름 (예 :)을 지정 _shared_null_ptr_type하고 nullPtr객체 정의를 별도의 .cpp 파일 로 이동 한 extern다음 헤더 파일에 선언을 추가 해야합니다. 클래스가 정의됩니다.


음, 이것은 합법적입니다.

shared_ptr<Foo> foo;  /* don't assign */

그리고이 상태에서는 아무것도 가리 키지 않습니다. 이 속성을 테스트 할 수도 있습니다.

if (foo) {
    // it points to something
} else {
    // no it doesn't
}

그러니 이렇게하지 않는 이유 :

std::vector < shared_ptr<Foo> > vec;
vec.push_back (shared_ptr<Foo>);   // push an unassigned one

C ++ 0X, 당신은 간단하게 변환 할 수 있습니다 nullptrstd::shared_ptr:

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(nullptr);

.NET에 대한 전역 nullPtr선언 할 수 shared_ptr<Foo>있습니다. 전역 네임 스페이스를 오염한다면, 당신은 무엇을 글로벌 부를 것 nullPtr를 들어 shared_ptr<Bar>?

일반적으로 포인터 클래스에서 null ptr을 static으로 선언합니다.

#include <boost\shared_ptr.hpp>

class Foo; // forward decl
typedef boost::shared_ptr<Foo> FooPtr;
class Foo
{
public:
    static FooPtr Null;
}
...
// define static in cpp file
FooPtr Foo::Null;
...
// use Foo Null
vec.push_back(Foo::Null);

이렇게하면 각 클래스에 정적 Null이 있습니다.


여기에 좀 더 간단하고 잘 작동하는 것이 있습니다.

( remember that typedef is your friend ):

#include    <cstdlib>
#include    <vector>
#include    <iostream>
#include    <boost/shared_ptr.hpp>

typedef boost::shared_ptr< std::vector<char> > CharVecHandle;

inline CharVecHandle newCharVec(std::vector<char>::size_type size) {
    return CharVecHandle(new std::vector<char>(size));
}

inline CharVecHandle newCharVec(void) {
    return CharVecHandle();
}

int main ( void )
{
    CharVecHandle cvh = newCharVec();

    if (cvh == NULL) 
        std::cout << "It's NULL" << std::endl;
    else 
        std::cout << "It's not NULL" << std::endl;

    std::vector< CharVecHandle > cvh_vec;

    cvh_vec.push_back(newCharVec(64));
    cvh_vec.push_back(newCharVec());

    // or call the NULL constructor directly
    cvh_vec.push_back(CharVecHandle());

    return EXIT_SUCCESS;
}

Yes, declare a global static null pointer.

ReferenceURL : https://stackoverflow.com/questions/621220/null-pointer-with-boostshared-ptr

반응형