簡體   English   中英

返回原始類型的數據成員作為const引用?

[英]Returning data members of primitive types as a const reference?

示例:我有一個名為Class的類,它有一個數據成員std :: string m_nameint 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM