• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            平凡的世界

            神鷹忽展翅,頭頂青天飛
            隨筆 - 10, 文章 - 0, 評(píng)論 - 34, 引用 - 0
            數(shù)據(jù)加載中……

            [原][譯] Tips for STL and Generic Programming-關(guān)于STL與泛型編程的忠告

            原文地址:http://tmh-coding-tips.blogspot.com/2008/09/cc-tips-for-stl-and-generic-programming.html

             

            [C/C++] - Tips for STL and Generic Programming

            關(guān)于STL“泛型”編程的忠告(v1.5

            Translated By Phoenix(E-Mail:phoenix8848@gmail.com)

                   Tip 15: The Location of Template Definitions

                   忠告15:模板定義的位置

                   Normally, you declare functions and classes in a .h file and place their definition in a separate .cpp file. With templates, this practice isn't really useful because the compiler must see the actual definition (i.e., the body) of a template, not just its declaration, when it instantiates a template. Therefore, it's best to place both the template's declaration and definition in the same .h file. This is why all STL header files contain template definitions. 
                   通常你在.h文件中聲明函數(shù)與類而把它們的實(shí)現(xiàn)放在若干個(gè).cpp文件中(以使聲明與實(shí)現(xiàn)分開)。使用模板的時(shí)候這樣的做法作用不大因?yàn)榫幾g器在實(shí)例化一個(gè)類模板時(shí)必須顯式地獲得類模板的實(shí)際定義(例如函數(shù)體),而不僅僅是它的聲明。所以最好是把類模板的聲明和實(shí)現(xiàn)放在同一個(gè)頭文件中。這就是為什么所有的STL(標(biāo)準(zhǔn)模板庫,即Standard Template Library,是一個(gè)C++軟件庫,也是C++標(biāo)準(zhǔn)程式庫的一部分)頭文件都包含模板的實(shí)現(xiàn)。
                  
            In the future, when compilers support the "export" keyword, it will be possible to use only the template's declaration and leave the definition in a separate source file.

                   將來當(dāng)編譯器支持“export”命令時(shí),有可能只需要模板的聲明而將它的實(shí)現(xiàn)放在單獨(dú)的源文件中。

                   Tip 16: Standard Base Classes for Function Object

                   忠告16:函數(shù)對(duì)象的標(biāo)準(zhǔn)基類

                   To simplify the process of writing function objects, the Standard Library provides two class templates that serve as base classes of user-defined function objects: std::unary_function and std::binary_function. Both are declared in the header “functional”. As the names suggest, unary_function serves as a base class of function objects taking one argument and binary_function serves as a base class of function objects taking two arguments. The definitions of these base classes are as follows:

                   為了簡(jiǎn)便地處理寫入函數(shù)對(duì)象,標(biāo)準(zhǔn)庫提供了兩個(gè)類模板以作為用戶自定義函數(shù)對(duì)象的基類:std::unary_functionstd::binary_funcation。這兩個(gè)模板都聲明在頭文件“functional”中。正如模板名字所示,unary_funcation作為單參數(shù)函數(shù)對(duì)象的基類而binary_function作為雙參數(shù)函數(shù)對(duì)象的基類。這兩個(gè)基類的定義如下所示:

             

             1template <class Arg, class Res> 
             2struct unary_function 
             3{
             4    typedef Arg argument_type;
             5    typedef Res result_type;
             6}
            ;
             7
             8template <class Arg, class Arg2, class Res> 
             9struct binary_function 
            10{
            11    typedef Arg first_argument_type;
            12    typedef Arg2 second_argument_type;
            13    typedef Res result_type;
            14}
            ;
            15
            16

             

                   These templates don't provide any useful functionality. They merely ensure that arguments and return values of their derived function objects have uniform names. In the following example, the predicate is_vowel, which takes one argument, inherits from unary_function:

                   這兩個(gè)模板并沒有提供任何有用的功能。它們僅僅是為了保證派生出來的函數(shù)對(duì)象的參數(shù)與返回值具有不同的名字。在下面的例子中聲明了從unary_function派生的_vowel,它只有一個(gè)參數(shù)。

             

             1template <class T> 
             2class is_vowel: public unary_function<T, bool>
             3{
             4public:
             5    bool operator ()(T t) const
             6    {
             7        if ((t=='a')||(t=='e')||(t=='i')||(t=='o')||(t=='u'))
             8            return true;
             9        else
            10            return false;
            11    }

            12}
            ;

             

                   Tip 17: Storing Dynamically Allocated Objects in STL Containers

                   忠告17:在標(biāo)準(zhǔn)模板庫容器中保存動(dòng)態(tài)生成的對(duì)象

                   Suppose you need to store objects of different types in the same container. Usually, you do this by storing pointers to dynamically allocated objects. However, instead of using named pointers, insert the elements to the container as follows:

                   假設(shè)你需要在一個(gè)容器中存儲(chǔ)不同的對(duì)象。通常你會(huì)通過保存動(dòng)態(tài)生成對(duì)象的指針來實(shí)現(xiàn)。無論如何不要用命名的指針,而是像下面所示的這樣添加元素到容器中:

            1class Base {};
            2class Derived : public Base{};
            3
            4std::vector<Base *> v;
            5v.push_back(new Derived);
            6v.push_back(new Base);



                  
            This way you ensure that the stored objects can only be accessed through their container. Remember to delete the allocated objects as follows:

                   這樣你可以保證存儲(chǔ)的對(duì)象只能通過容器訪問到。切記要用下面所示的方法釋放對(duì)象:

             

            1delete v[0];
            2delete v[1];
            3

             

                   Tip 18: Treating a Vector as an Array

                   忠告18:將向量容器看作是數(shù)組

                   Suppose you have a vector of int and function that takes int *. To obtain the address of the internal array of the vector v and pass it to the function, use the expressions &v[0] or &*v.front(). For example:

                   假設(shè)你有一個(gè)保存整型變量的向量容器和一個(gè)處理整型指針int*的函數(shù)。為了獲得向量容器v中的內(nèi)部數(shù)組并把它傳遞給函數(shù),應(yīng)該使用表達(dá)式&v[0]或者&*v.front(),如示例:

             1void func(const int arr[], size_t length );
             2
             3int main()
             4{
             5    vector<int> vi;
             6    //.. fill vi
             7    func(&vi[0], vi.size());
             8}

             9
            10


                   It's safe to use &vi[0] and &*v.front() as the internal array's address as long as you adhere to the following rules: First, func() shouldn't access out-of-range array elements. Second, the elements inside the vector must be contiguous. Although the C++ Standard doesn't guarantee that yet, I'm not aware of any implementation that doesn't use contiguous memory for vectors. Furthermore, this loophole in the C++ Standard will be fixed soon.

                   如果你能遵循下面的規(guī)則使用&vi[0]&*v.front()作為內(nèi)部數(shù)組的地址是安全的:第一,func()函數(shù)不能試圖訪問超出范圍的數(shù)組元素。第二,向量容器內(nèi)的元素必須是連續(xù)的。盡管C++標(biāo)準(zhǔn)并不要求如此,但我不知道有別的為容器實(shí)現(xiàn)不使用連續(xù)內(nèi)存。而且,C++標(biāo)準(zhǔn)不久就會(huì)修補(bǔ)這個(gè)漏洞。

                   Tip 19: Dynamic Multidimensional Arrays and Vectors

                   忠告19:動(dòng)態(tài)多維數(shù)組與容器

                   You can allocate multidimensional arrays manually, as in:

                   通常你會(huì)像下面的方式來分配多維數(shù)據(jù):

             

             1int (*ppi) [5]=new int[4][5]; /*parentheses required*/
             2
             3/*fill array..*/
             4
             5ppi[0][0= 65;
             6ppi[0][1= 66;
             7ppi[0][2= 67;
             8
             9//..
            10
            11delete [] ppi;

             

                   However, this style is tedious and error prone. You must parenthesize ppi to ensure that the compiler parses the declaration correctly, and you must delete the allocated memory. Worse yet, you can easily bump into buffer overflows. Using a vector of vectors to simulate a multidimensional array is a significantly superior alternative:

                   可是這種做法是冗長(zhǎng)而且非常容易出錯(cuò)。你必須把ppi放入括號(hào)內(nèi)以便編譯器可以正確地分析這些聲明,并且(最后)你必須(顯式地)地釋放這些分配的內(nèi)存空間。更糟糕的是,你會(huì)很容易地造成緩沖溢出。使用“容器之容器”來模擬多維數(shù)組是一種高明得多的選擇。

             1#include <vector>
             2#include <iostream>
             3using namespace std;
             4
             5int main()
             6{
             7    vector<vector<int>> v; /*two dimensions*/
             8    v.push_back(vector<int>()); /*create v[0]*/
             9    v.push_back(vector<int>()); /*create v[1]*/
            10    v[0].push_back(15); /*assign v[0][0]*/
            11    v[1].push_back(16); /*assign v[1][0]*/
            12}


                   Because vector overloads operator [], you can use the [][] notation as if you were using a built-in two-dimensional array:

                   因?yàn)槿萜髦剌d了操作符[],所以你可以用[][]來操作就如同使用內(nèi)置的二維數(shù)組。

             

            1cout<<v[0][0]; 
            2cout<<v[1][0];

             

                   The main advantages of using a vector of vectors are two: vector automatically allocates memory as needed. Secondly, it takes care of deallocating memory so you don't have to worry about potential memory leaks.

                   使用“容器之容器”有兩個(gè)主要的好處:第一,容器會(huì)在需要時(shí)自動(dòng)分配內(nèi)存。第二,容器可以自動(dòng)回收內(nèi)存所以你不必操心潛在的內(nèi)存泄漏。

             

                   Tip 20: Why You Shouldn't Store auto_ptr Objects in STL Containers

                   忠告20:為什么不能在標(biāo)準(zhǔn)模板庫容器中存儲(chǔ)auto_ptr

                   The C++ Standard says that an STL element must be "copy-constructible" and "assignable." These fancy terms basically mean that for a given class, assigning and copying one object to another are well-behaved operations. In particular, the state of the original object isn't changed when you copy it to the target object.

                   C++標(biāo)準(zhǔn)中說一個(gè)STL元素必須是可復(fù)制構(gòu)造(copy-constructible)和可賦值(assignable)的。這些充滿科幻色彩的詞匯的基本意思是對(duì)于一個(gè)給定的類,對(duì)象間的賦值與復(fù)制是一種表現(xiàn)良好的操作。特別的,源對(duì)象被復(fù)制給一個(gè)目標(biāo)對(duì)象時(shí)源對(duì)象不會(huì)有任何改變。

                   This is not the case with auto_ptr, though: copying or assigning one auto_ptr to another makes changes to the original in addition to the expected changes in the copy. To be more specific, the original object transfers ownership of the pointer to the target, thus making the pointer in the original null. Imagine what would happen if you did something like this:

                   這不適用于auto_ptr。因?yàn)椋岩粋€(gè)auto_ptr對(duì)象復(fù)制或賦值給另一個(gè)對(duì)象會(huì)引起原始對(duì)象的改變從而引起對(duì)象副本的改變。更細(xì)節(jié)地看,原始對(duì)象把指針的權(quán)限傳遞給了目標(biāo)對(duì)象,這使源對(duì)象中的指針變成空指針。設(shè)想當(dāng)你進(jìn)行下面這樣操作的時(shí)候會(huì)發(fā)生什么:

             1std::vector<auto_ptr<Foo>> vf;/*a vector of auto_ptr's*/
             2
             3// ..fill vf
             4
             5int g()
             6{
             7    std::auto_ptr<Foo> temp=vf[0]; /*vf[0] becomes null*/
             8}

             9
            10


                   When temp is initialized, the pointer of vf[0] becomes null. Any attempt to use that element will cause a runtime crash. This situation is likely to occur whenever you copy an element from the container. Remember that even if your code doesn't perform any explicit copy or assignment operations, many algorithms (std::swap(), std::random_shuffle() etc.) create a temporary copy of one or more container elements. Furthermore, certain member functions of the container create a temporary copy of one or more elements, thereby nullifying them. Any subsequent attempt to the container elements is therefore undefined.

                   當(dāng)臨時(shí)對(duì)象被初始化,vf[0]的指針變?yōu)榭铡H魏卧噲D使用這個(gè)元素都會(huì)引起運(yùn)行時(shí)崩潰。無論什么時(shí)候你從容器復(fù)制這個(gè)元素都會(huì)引發(fā)這種意外。切記即使你的代碼不進(jìn)行任何顯示的復(fù)制與賦值操作,很多算法(如std::swap(), std::random_shuffle())都會(huì)(隱蔽地)創(chuàng)建一個(gè)或更多容器元素的臨時(shí)副本。此外,容器的某些特定成員函數(shù)也會(huì)一個(gè)或列多元素的臨時(shí)副本,從而使這些元素失效。任何隨后的對(duì)容器元素的操作意圖都由此變?yōu)椴豢深A(yù)期的。

                   Visual C++ users often say that they have never encountered any problems with using auto_ptr in STL containers. This is because the auto_ptr implementation of Visual C++ (all versions thereof) is outdated and relies on an obsolete specification. When the vendor decides to catch up with the current ANSI/ISO C++ Standard and change its Standard Library accordingly, code that uses auto_ptr in STL containers will manifest serious malfunctions.

                   Visual C++用戶經(jīng)常說他們?cè)跇?biāo)準(zhǔn)模板容器中使用auto_ptr時(shí)從沒遇到什么問題。這是因?yàn)?/span>Visual C++auto_ptr的實(shí)現(xiàn)(目前為止所有的版本)都是過時(shí)的和參考了舊的規(guī)范說明。當(dāng)微軟決定采用現(xiàn)在的ANSI/ISO C++標(biāo)準(zhǔn)并據(jù)此對(duì)它的標(biāo)準(zhǔn)庫進(jìn)行更新時(shí),以前在標(biāo)準(zhǔn)模板容器中使用auto_ptr的代碼就會(huì)突現(xiàn)嚴(yán)重的問題。

                   To conclude, you shouldn't use auto_ptr in STL containers. Use either bare pointers or other smart pointer classes instead of auto_ptr (such classes are available at www.Boost.org).

                   作為結(jié)論,你最好不要在標(biāo)準(zhǔn)容器中使用auto_ptr,而是使用原始指針或別的智能指針類來代替auto_ptr(比如BOOST庫)

            posted on 2008-09-16 03:18 西門有悔 閱讀(1844) 評(píng)論(4)  編輯 收藏 引用

            評(píng)論

            # re: [原][譯] Tips for STL and Generic Programming  回復(fù)  更多評(píng)論   

            為什么不把英文弄掉?那樣會(huì)更方便閱讀
            2008-09-16 11:26 | 肥仔

            # re: [原][譯] Tips for STL and Generic Programming[未登錄]  回復(fù)  更多評(píng)論   

            因?yàn)樽髡哒J(rèn)為翻譯可能有錯(cuò),這個(gè)時(shí)候可以通過閱讀原文來解決疑問。
            2008-09-16 13:10 | 陳梓瀚(vczh)

            # re: [原][譯] Tips for STL and Generic Programming-關(guān)于STL與一般編程的忠告  回復(fù)  更多評(píng)論   

            那叫……泛型編程
            2008-09-18 12:47 | 還要姓名?

            # re: [原][譯] Tips for STL and Generic Programming-關(guān)于STL與泛型編程的忠告  回復(fù)  更多評(píng)論   

            @還要姓名?

            瀑布汗~~~謝謝你。改過來了。
            2008-09-24 15:29 | 西門有悔

            只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


            伊人久久一区二区三区无码| 久久免费观看视频| 亚洲va久久久噜噜噜久久天堂| 尹人香蕉久久99天天拍| 久久精品国产男包| 高清免费久久午夜精品| 久久精品国产亚洲Aⅴ香蕉| 四虎国产精品成人免费久久| 久久国产色AV免费观看| 亚洲伊人久久综合中文成人网 | 精品国际久久久久999波多野| 久久成人精品视频| 久久无码AV一区二区三区| 久久国产高清字幕中文| 亚洲?V乱码久久精品蜜桃 | 久久99精品久久久久久噜噜| 精品久久亚洲中文无码| 91精品国产高清久久久久久国产嫩草 | 999久久久免费精品国产| 午夜精品久久影院蜜桃| 色噜噜狠狠先锋影音久久| 久久久久久久女国产乱让韩| 久久人人爽人爽人人爽av | 国产午夜福利精品久久2021| 国产精品一区二区久久精品涩爱| av无码久久久久不卡免费网站| 亚洲欧洲精品成人久久曰影片| 一级做a爱片久久毛片| 国产精品欧美久久久天天影视| 国产色综合久久无码有码| 久久久久久精品免费免费自慰| 精品久久久久久99人妻| 国产福利电影一区二区三区久久老子无码午夜伦不 | 久久午夜综合久久| 久久久久国产精品麻豆AR影院| 国产免费久久精品丫丫| 久久成人国产精品一区二区| 狠狠人妻久久久久久综合蜜桃 | 久久久久一本毛久久久| 久久久久婷婷| 无码国内精品久久综合88 |