[英]Returning data members of primitive types as a const reference?
示例:我有一個名為Class的類,它有一個數據成員std :: string m_name和int m_value 。
為了避免不必要的復制,我這樣做。
const std::string& Class::name() const;
為了使功能一致,是否也可以對原始類型執行此操作?
const int& Class::value() const;
對於您的API用戶而言,這沒有什么區別。 他的代碼看起來像
Class c;
c.value(1940);
int x = c.value();
無論用哪種方式編寫。
如果您返回引用(您可能想要或可能不想要),他可能會做的一件事是
const int &x = c.value();
int &k = const_cast<int &>(x);
k++; // will change the internals of your object
這是你的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.