Last active
December 15, 2015 03:29
-
-
Save raimusyndrome/c7399e5d29e4eeb53f9c to your computer and use it in GitHub Desktop.
Boostのスマートポインタ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/scoped_ptr.hpp> | |
#include <boost/scoped_array.hpp> | |
int square( int* x ){ | |
int y = *x; | |
return y*y; | |
} | |
int main() { | |
// 生成 | |
boost::scoped_ptr<int> ptr(new int); | |
boost::scoped_array<int> arr(new int[10]); | |
// 代入・参照 | |
*ptr = 10; | |
for( int i = 0; i < *ptr; i++ ){ | |
arr[i] = i; | |
} | |
std::cout << *ptr << std::endl; | |
for( int i = 0; i < *ptr; i++ ){ | |
std::cout << "[" << i << "]:"<< arr[i] << std::endl; | |
} | |
// 要素数を変更(新たな領域を取得) | |
arr.reset(new int[20]); | |
*ptr = 5; | |
arr[10] = 20; | |
// 元の型のポインタが必要な場合 | |
std::cout << square(ptr.get()) << std::endl; | |
std::cout << square(&(arr.get())[10]) << std::endl; | |
// 解放処理は不要 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment