CリターンCONSTインデックス/関数参照

CリターンCONSTインデックス/関数参照

constのリターンインデックス/関数参照

私たちは知っているconst、それはされますが、変数の前にあるプラスが変更されるのを防止することを目的としてconstの機能が表現される前に追加しますか?その役割は、「関数参照/ポインタのリターンが変更されていないことを確認。」することです

以下の実施例を参照(のコードCPPコード・スニペット/ const_return_value.cpp)。

#include <iostream>
#include <vector>

const int f1(){
    return 3;
};

const char* f2(){
    return "abc";
};

std::vector<int> myvec = {0};

const std::vector<int>& f3(){
    return myvec;
}

int main(){
    int x = f1();
    //error: cannot initialize a variable of type 'char *' with an rvalue of type 'const char *'
    //char* s = f2();
    const char* s = f2();
    //error: binding value of type 'const vector<...>' to reference to type 'vector<...>' drops 'const' qualifier
    //std::vector<int>& v = f3();
    const std::vector<int>& v = f3();

    std::cout << "int: " << x << std::endl;
    std::cout << "const char*: " << s << std::endl;
    std::cout << "const vector&: " << v[0] << std::endl;

    return 0;
}

機能は、int f1()値ではなく、参照またはポインタを返すので、使用const改変int f1()無意味です。

const char* f2()戻り値はポインタである、そしてconst我々は唯一のことができます:戦場に出た単語を修正しf2()、戻り値が割り当てられているconst char*他の変数の種類、それに割り当てられていないchar*タイプの他の変数、が存在することになるcannot initialize a variable of type 'char *' with an rvalue of type 'const char *'間違いました。

関数のconst std::vector<int>& f3()戻り値が参照され、我々はまた、唯一の戻り値に割り当てることができ、const std::vector<int>&タイプ別の変数、それに割り当てられていないstd::vector<int>&タイプの他の変数、が存在することになるerror: binding value of type 'const vector<...>' to reference to type 'vector<...>' drops 'const' qualifier間違いました。

TensorRT/samples/common/buffers.h定義2つのバックホールconstメトリック/参照機能、戻り値が誤って変更されてから回避することができます。

template <typename AllocFunc, typename FreeFunc>
class GenericBuffer
{
public:
    //...
    const void* data() const
    {
        return mBuffer;
    }
    //...
private:
    //...
    void* mBuffer;
    //...
};
class BufferManager
{
public:
    //...
    const std::vector<void*>& getDeviceBindings() const
    {
        return mDeviceBindings;
    }
    //...
private:
    std::vector<void*> mDeviceBindings; //!< The vector of device buffers needed for engine execution
};

参考リンク

戻り値の型に無用型修飾子は、明確にするため、使用すべきですか?

公開された98元の記事 ウォンの賞賛9 ビュー50000 +

おすすめ

転載: blog.csdn.net/keineahnung2345/article/details/104084851