1つ目は new に関してです。
newの実装
デフォルトのoperator newの実装例
void * operator new ( std::size_t size ) throw( std::bad_alloc ) { if ( size == 0 ) size = 1 ; // Executes a loop: Within the loop, while( true ) { // the function first attempts to allocate the requested storage. void * ptr = std::malloc( size ) ; // if the attempt is successful if ( ptr != nullptr ) {// Returns a pointer to the allocated storage return ptr ; } // Otherwise, std::new_handler handler = std::set_new_handler( nullptr ) ; std::set_new_handler( handler ) ; // if the argument in the most recent call to set_new_handler() was a null pointer, if ( handler == nullptr ) {// throws bad_alloc. throw std::bad_alloc() ; } // Otherwise, the function calls the current new_handler function. handler() ; // If the called function returns, the loop repeats. } }
また、こちらだと少し実装が異なるようです。
libc++の方ですね。
LLVM Download Page
ダウンロードしてビルドしてみました。
// Implement all new and delete operators as weak definitions // in this shared library, so that they can be overridden by programs // that define non-weak copies of the functions. _LIBCPP_WEAK void * operator new(std::size_t size) _THROW_BAD_ALLOC { if (size == 0) size = 1; void* p; while ((p = ::malloc(size)) == 0) { // If malloc fails and there is a new_handler, // call it to try free up memory. std::new_handler nh = std::get_new_handler(); if (nh) nh(); else #ifndef _LIBCPP_NO_EXCEPTIONS throw std::bad_alloc(); #else break; #endif } return p; }
んーーー。
newってmalloc使ってたんだ!!
「they can be overridden by programs」これはなんのことを言っているのかサッパリですが・・・
newの実装自体が、libc++とlibstdc++で異なっている可能性があります。
libstdc++をどこで手に入れるのかわからなかったので調べていないのですが・・・
ここで疑問3つ出てきます。
1,void をreturn している。*
2,malloc使っているのに、どうやってコンストラクタ呼び出しているのか??
3,パラメータがstd::size_tになっている
1番目と3番めについては、
int * ptr = new int
という風に使いますが・・・
*int * ptr = static_cast<int >(new sizeof(int))
上記の実装では、このように書かなくてはならないはずです。
なぜこうは書かかなくてもエラーやwarningにならないのでしょうか??
2番目については、自分の持っている本にこうあります。
operator new や operator delete について、よく誤解があるが、コンストラクタやデストラクタの呼び出しの責任は持たない。
え??そうなの?
では、なんで、mallocを使った時はコンストラクタを呼び出さないのに、newの時は呼び出すのでしょうか??
2つ目は、演算子についてです。
1 #include<iostream> 2 3 int max(int a, int b){ 4 return a < b ? b : a; 5 } 6 7 int main(){ 8 int max(int, int = 3 + !(std::cout << ",")); 9 10 for(int i = 0 ; i < 10; i++) 11 std::cout << max(i); 12 std::cout << std::endl; 13 return 0; 14 } 15
,3,3,3,3,4,5,6,7,8,9
と出力されます。
おお!すごい!デフォルトパラメータにこんな事ができるんだぁ!
ここで疑問なのが、+!の演算子です。
この組み合わせは初めて見ました。
色々試してみました。
int max(int, int = 3 + (std::cout << ",")); //error int max(int, int = 3 - !(std::cout << ",")); //ok int max(int, int = 3 & !(std::cout << ",")); // 結果が変わる int max(int, int = 3 ~ !(std::cout << ",")); //error
できる組み合わせとできない組み合わせがあります。
!演算子がない、+演算子だけの場合はうまくいかないのが引っかかります。
+!の組み合わせにどのような意味があるのでしょうか??
g++ Linux 64bitです。
分かる方いたらお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/15 15:23
2018/08/15 15:25
2018/08/15 15:31
2018/08/15 15:41
2018/08/15 15:42
2018/08/15 15:44
2018/08/15 15:45
2018/08/15 15:51
2018/08/15 15:54
2018/08/16 04:25