C 回傳const指標/參考的函數

C 回傳const指標/參考的函數

回傳const指標/參考的函數

我們知道把const加在一個變數前面的用意是防止它被修改,那麼將const加在一個函數前是代表什麼呢?它的作用是"確保函數回傳的reference/pointer不被改變"。

參考以下例子(代碼放在cpp-code-snippets/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()回傳的是value而非reference或pointer,因此使用const修飾int f1()是無意義的。

const char* f2()回傳的則是一個pointer,這時const修飾字就會發揮作用了:我們只能將f2()的回傳值指定給const char*型別的變數,而不能指定給char*型別的變數,否則會出現 cannot initialize a variable of type 'char *' with an rvalue of type 'const char *' 的錯誤。

函數const std::vector<int>& f3()回傳的是一個reference,我們同樣只能將其回傳值指定給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中定義了兩個回傳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
};

參考連結

Should useless type qualifiers on return types be used, for clarity?

发布了98 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/104084851