gpt4 book ai didi

C++:在函数中使用共享指针作为参数是否可以,还是在浪费内存?

转载 作者:行者123 更新时间:2023-11-30 03:27:08 30 4
gpt4 key购买 nike

我几周前才开始学习 C++,所以我不是内存管理方面的专家(这在这种情况下非常重要,但我对计算机体系结构以及指针如何存储不了解信息)。这就是为什么我不确定使用 shared_ptr 作为函数参数是否浪费内存。

我正在制作的程序包含两个类,分别称为 Usuario 和 Product。第一个类表示 User 并有两个私有(private)变量:std::string m_name(引用的名称)和 float m_money(用户拥有的金钱数量),以及它们各自的 getter 和 setter。

第二类代表产品,有三个私有(private)变量:std::string m_name(产品名称),float m_price(它的价格), float m_iva(一种叫做 Impuesto sobre el Valor Agregado 的税,我设定为 12%,所以 m_iva = m_price x 0.12) 和float m_totalPrice(产品的最终价格,所以 m_totalPrice = m_price + m_iva),其中它们各自的 getter 和两个 setter 与 m_namem_price 相关。

用各自的 .h 和 .cpp 文件设置这些类后,我使用 std::shared_pointer<class> 在 main() 函数中创建了对象 > < em>objectName = std::make_shared<class> (parameters) 并使用 std::shared_pointer<class 将它们作为参数传递给其他函数> 不同的名称。例如,这是一个允许用户输入姓名和金额的函数:

void SetCurrentUser(std::shared_ptr<Usuario> defaultUser) //Not sure if this is efficient.
{
std::string userName; //Variable to which the user input will be stored
float money; //Variable to which the user input will be stored

std::cout << "Input your name: "; std::cin >> userName; defaultUser->SetName(userName); //Sets a new name to defaultUser
std::cout << "Input the amount of money you have: "; std::cin >> money; defaultUser->SetMoney(money); //Sets a new amount of money to defaultUser

}

这里有一个函数,它打印一个项目的信息并告诉用户他们是否可以购买。

    void PrintCurrentStatus(std::shared_ptr<Product> AnyProduct, std::shared_ptr<Usuario> User) //Not sure if this is efficient either
{
std::cout << "\n" << std::setprecision(3) << AnyProduct->GetName() << " + " << AnyProduct->GetPrice() << "$"
<< " + " << AnyProduct->GetIVA() << " IVA = " << AnyProduct->GetTotal()
<< "$" << std::endl; //Prints the product information like this: *line* *m_name* + *m_iva*IVA = *m_totalPrice*

if ( User->GetMoney() >= AnyProduct->GetTotal() ) { //If the user's amount money is equal to or greater than the total price of the product.
std::cout << "User is allowed to pay.";
}
else { //If the user's amount of money is less than the total price of the product.
std::cout << "User doesn't have enough money.";
}
}

这里是 main() 函数,我在其中创建了所有对象(包括我使用“”和 0 作为初始参数设置的用户):

int main()
{
std::shared_ptr<Usuario> CurrentUser = std::make_shared<Usuario>(" ", 0); //I created this object so that it can be set properly with the function SetCurrentUser
SetCurrentUser(CurrentUser); //Here the user sets it as they wish.
std::shared_ptr<Product> Product1 = std::make_shared<Product>("Butter", 10.56, 10); //Product1's name is Butter, costs 10.56 dollars and there are 10 units available
std::shared_ptr<Product> Product2 = std::make_shared<Product>("Milk", 5.45, 10); //Product2's name is "Milk", costs 5.45 dollars and there are 10 units of it available.
PrintCurrentStatus(Product1, CurrentUser); //Prints Product1's information and tells the user whether they can buy it or not.
PrintCurrentStatus(Product2, CurrentUser); //Prints Product2's information and tells the user whether they can buy it or no.

std::cin.ignore(); //We need to erase the contents of cin.
std::cin.get(); //Waits until the user presses enter.
return 0; //The program ends here.
}

所有这些函数都位于同一个 .cpp 文件中。

所以,综上所述,该程序的行为完全符合我的要求。但是,我确实想知道:我是否通过将 std::shared_ptr 作为与在主函数内创建的对象的共享指针相对应的函数参数来浪费内存?是否有更有效的方法来获得相同的结果?

最佳答案

从技术上讲,您是在“浪费内存”,因为 std::shared_ptr 由两个内部指针组成(具有典型的 C++ 实现),因此传递 std::shared_ptr 按值作为函数的参数最终实际上传递了两个指针;在传递一个普通指针参数时,嗯,显然传递了一个。

那又怎样?使用智能指针的好处超过了轻微的开销。

但是,您可以做得更好。在几乎所有用例中,您都可以通过引用传递参数,而不是:

void SetCurrentUser(const std::shared_ptr<Usuario> &defaultUser) 

对于典型的 C++ 实现,这最终会传递一个实际的指针,并且“浪费”与传递普通指针一样多的堆栈。您可以获得使用智能指针的所有好处,同时在堆栈上受到相同数量的宝贵字节的惩罚。当然,按值传递参数与按引用传递参数之间存在一些根本区别。但是对于您现在编写的几乎所有简单、基本的程序,在功能上没有区别,您的 C++ 书籍应该向您充分解释它们是什么,当它开始变得重要时。

通常,间接引用可能会带来一些额外的运行时开销,但这很可能会通过不必更新智能指针中保存的内部引用计数而节省几个 CPU 周期来抵消;而且,无论如何,在现代多 ghz 平台上,任何人都不会注意到它,除非使用原子钟或其他东西。

关于C++:在函数中使用共享指针作为参数是否可以,还是在浪费内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47609291/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com