이전 글에 이어서 포스팅 합니다. VC++ 2008에서 TR1 구현을 일부 지원합니다. 이전 프로젝트에서는 Boost C++ Library를 쓰고 있었는데 이런 Library를 연결시키지 않고 컴파일 할 수 있다는 것이 매우 좋은 소식인 것 같습니다.

 
도움말에 첨부된 예제 소스를 일부 공유해봅니다.

// bind.cpp
// compile with /EHsc
#include <functional>
#include <algorithm>
#include <iostream>
 
using namespace std::tr1::placeholders;
 
void square(double x)
    {
    std::cout << x << "^2 == " << x * x << std::endl;
    }
 
void product(double x, double y)
    {
    std::cout << x << "*" << y << " == " << x * y << std::endl;
    }
 
int main()
    {
    double arg[] = {1, 2, 3};
 
    std::for_each(&arg[0], &arg[3], square);
    std::cout << std::endl;
 
    std::for_each(&arg[0], &arg[3], std::tr1::bind(product, _1, 2));
    std::cout << std::endl;
 
    std::for_each(&arg[0], &arg[3], std::tr1::bind(square, _1));
 
    return (0);
    }
1^2 == 1
2^2 == 4
3^2 == 9
 
1*2 == 2
2*2 == 4
3*2 == 6


위에서 처럼 bind()와 placeholder(_1, _2, ... )가 생겨서 함수형 포인터를 다루기가 매우 수월해졌습니다. mem_fn()과 함께 쓴다면, 여러가지 상황에서 응용할 수 있을 것 같습니다.

// sp_construct.cpp
// compile with /EHsc
#include <memory>
#include <iostream>
 
struct deleter
    {
    void operator()(int *p)
        {
        delete p;
        }
    };
 
int main()
    {
    std::tr1::shared_ptr<int> sp0;
    std::cout << "(bool)sp0 == " << std::boolalpha
        << (bool)sp0 << std::endl;
 
    std::tr1::shared_ptr<int> sp1(new int(5));
    std::cout << "*sp1 == " << *sp1 << std::endl;
 
    std::tr1::shared_ptr<int> sp2(new int(10), deleter());
    std::cout << "*sp2 == " << *sp2 << std::endl;
 
    std::tr1::shared_ptr<int> sp3(sp2);
    std::cout << "*sp3 == " << *sp3 << std::endl;
 
    std::tr1::weak_ptr<int> wp(sp3);
    std::tr1::shared_ptr<int> sp4(wp);
    std::cout << "*sp4 == " << *sp4 << std::endl;
 
    std::auto_ptr<int> ap(new int(15));
    std::tr1::shared_ptr<int> sp5(ap);
    std::cout << "*sp5 == " << *sp5 << std::endl;
 
    return (0);
    }
(bool)sp0 == false
*sp1 == 5
*sp2 == 10
*sp3 == 10
*sp4 == 10
*sp5 == 15


TR1 스펙 중에 가장 매력적인 것 중에 하나가 이 shared_ptr/weak_ptr이 아닌가 싶습니다. 포인터를 Class화시켜서 다루면서 알아서 Reference Count계산과 Garbages Collecting을 해주니 C++에서도 Java나 C#처럼 메모리 관리에 대해서 별로 신경 쓰지 않고 프로그래밍 할 수 있습니다. 위의 예제에서처럼 weak_ptr과 shared_ptr간의 상호 변환 그리고, auto_ptr의 이용이 가능합니다.
 ㅎ

Posted by U∙Seung