- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我几周前才开始学习 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_name 和 m_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/
简而言之:我想从可变参数模板参数中提取各种选项,但不仅通过标签而且通过那些参数的索引,这些参数是未知的 标签。我喜欢 boost 中的方法(例如 heap 或 lockfree 策略),但想让它与 S
我可以对单元格中的 excel IF 语句提供一些帮助吗? 它在做什么? 对“BaselineAmount”进行了哪些评估? =IF(BaselineAmount, (Variance/Baselin
我正在使用以下方法: public async Task Save(Foo foo,out int param) { ....... MySqlParameter prmparamID
我正在使用 CodeGear RAD Studio IDE。 为了使用命令行参数测试我的应用程序,我多次使用了“运行 -> 参数”菜单中的“参数”字段。 但是每次我给它提供一个新值时,它都无法从“下拉
我已经为信用卡类编写了一些代码,粘贴在下面。我有一个接受上述变量的构造函数,并且正在研究一些方法将这些变量格式化为字符串,以便最终输出将类似于 号码:1234 5678 9012 3456 截止日期:
MySql IN 参数 - 在存储过程中使用时,VarChar IN 参数 val 是否需要单引号? 我已经像平常一样创建了经典 ASP 代码,但我没有更新该列。 我需要引用 VarChar 参数吗?
给出了下面的开始,但似乎不知道如何完成它。本质上,如果我调用 myTest([one, Two, Three], 2); 它应该返回元素 third。必须使用for循环来找到我的解决方案。 funct
将 1113355579999 作为参数传递时,该值在函数内部变为 959050335。 调用(main.c): printf("%d\n", FindCommonDigit(111335557999
这个问题在这里已经有了答案: Is Java "pass-by-reference" or "pass-by-value"? (92 个回答) 关闭9年前。 public class StackOve
我真的很困惑,当像 1 == scanf("%lg", &entry) 交换为 scanf("%lg", &entry) == 1 没有区别。我的实验书上说的是前者,而我觉得后者是可以理解的。 1 =
我正在尝试使用调用 SetupDiGetDeviceRegistryProperty 的函数使用德尔福 7。该调用来自示例函数 SetupEnumAvailableComPorts .它看起来像这样:
我需要在现有项目上实现一些事件的显示。我无法更改数据库结构。 在我的 Controller 中,我(从 ajax 请求)传递了一个时间戳,并且我需要显示之前的 8 个事件。因此,如果时间戳是(转换后)
rails 新手。按照多态关联的教程,我遇到了这个以在create 和destroy 中设置@client。 @client = Client.find(params[:client_id] || p
通过将 VM 参数设置为 -Xmx1024m,我能够通过 Eclipse 运行 Java 程序-Xms256M。现在我想通过 Windows 中的 .bat 文件运行相同的 Java 程序 (jar)
我有一个 Delphi DLL,它在被 Delphi 应用程序调用时工作并导出声明为的方法: Procedure ProduceOutput(request,inputs:widestring; va
浏览完文档和示例后,我还没有弄清楚 schema.yaml 文件中的参数到底用在哪里。 在此处使用 AWS 代码示例:https://github.com/aws-samples/aws-proton
程序参数: procedure get_user_profile ( i_attuid in ras_user.attuid%type, i_data_group in data_g
我有一个字符串作为参数传递给我的存储过程。 dim AgentString as String = " 'test1', 'test2', 'test3' " 我想在 IN 中使用该参数声明。 AND
这个问题已经有答案了: When should I use "this" in a class? (17 个回答) 已关闭 6 年前。 我运行了一些java代码,我看到了一些我不太明白的东西。为什么下
我输入 scroll(0,10,200,10);但是当它运行时,它会传递字符串“xxpos”或“yypos”,我确实在没有撇号的情况下尝试过,但它就是行不通。 scroll = function(xp
我是一名优秀的程序员,十分优秀!