如何在c++中拥有私有成员变量和对它们的引用
How to have private member variables and references to them in c++
我正在尝试拥有一个私有实例变量,并使用一个getter方法来返回对该私有ivar的引用(我知道我可以将该ivar公开)。
当我在使用getter方法后修改变量时,它似乎是在修改ivar的副本,而不是原始副本。有什么想法吗?
#include <iostream>
#include <tr1/unordered_map>
#include <tr1/functional>
#include <tr1/utility>
typedef std::tr1::unordered_map<std::string, std::string> umap_str_str;
class Parent {
public:
//add an item to the private ivar
void prepareIvar(bool useGetter)
{
std::pair<std::string, std::string> item("myKey" , "myValue");
if(useGetter){
//getting the reference and updating it doesn't work
umap_str_str umap = getPrivateIvar();
umap.insert( item );
}else {
//accessing the private ivar directly does work
_UMap.insert( item );
}
}
void printIvar()
{
std::cout << "printIvarn";
for( auto it : _UMap){
std::cout << "tKEY: " << it.first << "VALUE: " << it.second << std::endl;
}
}
//get a reference to the private ivar
umap_str_str& getPrivateIvar()
{
return _UMap;
}
private:
umap_str_str _UMap;
};
int main(int argc, const char * argv[])
{
Parent *p = new Parent();
p->prepareIvar(true);//use the getter first
p->printIvar();//it doesn't print the right info
p->prepareIvar(false);//access the private ivar directly
p->printIvar();//prints as expected
return 0;
}
在这一行中,您使用的是getPrivateVar()方法,它返回一个引用。但是,您将它存储在umap_str_str:类型的变量中
umap_str_str umap = getPrivateIvar();
现在正在创建一个新的umap_str_str对象,它将是_umap私有成员的副本。你需要使用一个参考:
umap_str_str &umap(getPrivateIvar());
您正在复制引用。您需要:
umap_str_str& umap = getPrivateIvar();
getPrivateIvar()
确实为您的会员返回了一个别名,但是当您进行时
umap_str_str umap = getPrivateIvar();
您可以有效地调用副本构造函数,从而处理副本。
您可以编写
umap_str_str& umap (getPrivateIvar());
否则,您将创建地图的副本
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 如果非动态变量被指针引用,何时超出范围?
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 为什么C++可以使用未初始化的成员变量(引用或指针 *NOT 值复制*)来初始化其父类的成员变量
- 地址运算符是否返回变量引用的对象的地址
- 未在另一个函数中设置变量引用的问题
- 英特尔样式内联程序集和 AT&T 样式中的变量引用,C++
- 将成员变量引用为类成员
- 从静态变量引用非静态变量会使非静态变量先于静态变量进行析构函数
- 何时解析 C++11 lambda 表达式中的变量引用
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- C++强制对变量引用进行编译优化,使之成为直接的
- Boost变量引用和相等比较
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员
- 为什么要在Java中生成变量引用数组
- 捕获和调试对移动lambda内部局部变量引用的无效使用
- 在变量初始化后更改变量引用
- 从'C'程序中提取变量定义和变量引用