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
};