【发布时间】:2020-09-01 18:01:16
【问题描述】:
过去几天我一直在研究引用和智能指针,但我仍然不知道什么时候使用。
特别是对于我正在尝试编写的非常简单的程序。 对象值不应该被共享而只被修改的地方是通过从 X 或 Y 方法返回其类型的值。
如果我没记错的话,引用更容易记忆,但只指一件事。 智能指针更稳定,可以重新映射以指向其他东西。
第一个问题:
对于像下面示例中的对象的简单更改,是否甚至需要创建引用或指针? 我想从长远来看,随着程序的复杂性增加,初始化对象做他们的事情可能会产生延迟问题等等......
第二个问题:
据我了解,引用对象将通过引用对象作为方法中的参数而不是将对象复制粘贴到其中来减轻内存压力? smart_ptr 做同样的事情吗?
类的头文件:
-Items.h-
class Health_Potion
{
public:
int qty = 0;
static int add_health_potion(int current, int add);
};
方法的 cpp 文件:
-Items.cpp-
int Health_Potion::add_health_potion(int current, int add)
{
int new_current = current + add;
cout << add << " potion added to your inventory.\n";
cout << "Quantity available: " << new_current << "\n";
return current + add;
}
主要功能:
-Main-
int main()
{
// Initializing the method to be used:
// Question: Should this also be stored into a smart_ptr or referenced to?
Health_Potion add_method;
add_method.add_health_potion;
______________________________________________
// The unique_ptr version I got:
std::unique_ptr<Health_Potion> entity(new Health_Potion); //Unique_ptr
entity -> qty = add_method.add_health_potion(rentity -> qty, roll); //returning new value to the pointer through method
______________________________________________
//The reference version I got:
Health_Potion obj1;
int & refqty = obj1.qty; //reference to object of qty created
refqty = add_method.add_health_potion(refqty, roll); //returning new value to the reference through method
}
原谅我的新手。
感谢您的宝贵时间:)。
【问题讨论】:
标签: c++ object methods reference smart-pointers