簡體   English   中英

奇怪? 行為的行為

[英]Strange? behaviour of cout

為什么執行此代碼:

// DefaultAny.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <exception>

using std::cout;

template<class T>
struct NoReturnPolicy 
{
    static void calculate(T& result, const T& source)
    {
        result = source;
    }
};

template<class T>
struct ReturnPolicy 
{
    static T& calculate(T& result, const T& source)
    {
        result = source;
        return result;
    }
};


template<class T>
struct ThrowPolicy 
{
    static void check(T* ptr)
    {
        cout << "ThrowPolicy";
        struct Nullptr: public std::exception{};

        if(!ptr)
        {
            throw Nullptr("Nullptr not allowed"); 
        }
    }
};

template<class T>
struct NoThrowPolicy 
{
    static T* check(T* ptr)
    {
        cout << "NoThrowPolicy";
        if(!ptr)
        {
            return nullptr;
        }
        else
        {
            return ptr;
        }
    }
};


/*
If pointer already points at 
something no assignement is being done
*/
template<class T, class ThrowingPolicy>
struct NoAssignPolicy 
{
    static T* check(T* dest,const T*const src)
    {
        cout << "NoAssignPolicy";
        if (!ThrowPolicy::check(dest))
        {
            dest = operator new(sizeof(T));
            new (dest) T(*src);
        }

    }
};

template<class T,class ThrowingPolicy>
struct NoCheckPolicy
{
    static void check(T* p)
    {
        cout << "NoCheckPolicy";
    }
};


template<class T,class ThrowingPolicy>
struct CheckPolicy
{
    static void check(T* p)
    {
        cout << "CheckPolicy";
        ThrowingPolicy::check(p);
    }
};


template<
         class T,
         class ThrowingPolicy = NoThrowPolicy<T>,
         class CheckingPolicy = NoCheckPolicy<T,ThrowingPolicy>,  
         class AssigningPolicy = NoAssignPolicy<T,ThrowingPolicy>,
         class ReturningPolicy = NoReturnPolicy<T>
        >
struct BreadSlicer
{
    BreadSlicer()
    {
        cout << "Type: " << typeid(T).name() << '\n';
            cout << "ThrowingPolicy: " << ThrowingPolicy::check(0) << '\n'; //  
//<<<---------The second call to cout makes output on my console:  
//NoThrowPolicy:"NoSpace"ThrowingPolicy:"Space"000000
        }
    };

    //The words NoSpace and Space do not actually appear in my console ;) and they are in the opposite order.



int _tmain(int argc, _TCHAR* argv[])
{
    BreadSlicer<int> a;
    return 0;

}

請參閱main以上第一個結構中的注釋。

這是未指定行為的結果。 如果你有:

cout << a() << b() << c() << endl;

沒有定義a,b和c的執行順序(是的,它們的結果以可預測的順序添加到cout流中,但是函數的執行未按定義的順序進行)。

如果您的問題是為什么“ NoThrowPolicy”在“ ThrowingPolicy”之前獲得輸出,則答案是沒有序列點可以保證對ThrowingPolicy::check(0)的調用和對operator<<(cout, "ThrowingPolicy: ") 允許C ++以任何順序調用這些函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM