이전 글에 이어서 포스팅 합니다. 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
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
*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의 이용이 가능합니다.
ㅎ
'정보 공유터' 카테고리의 다른 글
| 싸이월드 행복한 클릭(미니애드), 진화(?) 한다. (0) | 2008/01/31 |
|---|---|
| 티스토리에서 IFRAME 삽입하기... (4) | 2008/01/31 |
| [PowerPoint] 그룹으로 묶인 도형과 텍스트를 한번에 줄이기/늘리기 (4) | 2008/01/27 |
| Microsoft Visual C++ 2008, TR1 구현 Example (2) | 2008/01/10 |
| Visual C++ 2008, MFC 9 업데이트 버전 발표 (6) | 2008/01/09 |
| Silverlight 2.0, 미국 올림픽 중계에 사용 된다. (0) | 2008/01/08 |
| IronPython Studio December 2007 CTP Release (0) | 2008/01/07 |
