简体   繁体   English

C++ 成员函数(getters)

[英]C++ Member Functions (getters)

I've seen people define a member function like this:我见过人们这样定义成员 function:

void getValue(int& v)
{
    v = m_value;
}

and also like this:也像这样:

int getValue()
{
    return m_value;
}

I guess the first saves memory?我猜第一个保存 memory? Is that the only time you would use the first type of get-function?那是你唯一一次使用第一种类型的 get 函数吗? The second seems a lot more convenient.第二个似乎更方便。

I thought I would godbolt it for you我以为我会为你神栓

source来源

#include <iostream>
struct Foof{
    int m_val;

   Foof(int v){
      m_val = v;
}

void woodle()
{
    if(m_val > 42)
       m_val++;
    else
       m_val--;
      
}
void Get1(int &v)
{
    v = m_val;
}

int Get2()
{
    return m_val;
}
};

int main(int c, char**v){
    int q;
    std::cin >> q;
    Foof f1(q);
    std::cin >> q;
    Foof f2(q);

    f1.woodle();
    f2.woodle();
    int k;
    f1.Get1(k);

    int j = f2.Get2();
    std::cout << k << j;
}

the woodle function and the cin to initialize is to make the compiler think a bit woodle function 和 cin 初始化是为了让编译器思考一下

I have 2 foofs otherwise the compiler goes "well I know the answer to this question" when I call Get2 after Get1我有 2 个错误,否则当我在 Get1 之后调用 Get2 时,编译器会“我知道这个问题的答案”

compiled with -03 - ie optimize hard.用-03编译——即努力优化。 The code comes out as (gcc)代码输出为 (gcc)

 pushq %rbx
  movl $_ZSt3cin, %edi
  subq $16, %rsp
  leaq 12(%rsp), %rsi
  call std::basic_istream<char, std::char_traits<char> >::operator>>(int&)
  movl 12(%rsp), %ebx
  leaq 12(%rsp), %rsi
  movl $_ZSt3cin, %edi
  call std::basic_istream<char, std::char_traits<char> >::operator>>(int&)
  movl 12(%rsp), %eax
  movl $_ZSt4cout, %edi

  leal 1(%rbx), %edx
  cmpl $43, %ebx
  leal -1(%rbx), %esi
  cmovge %edx, %esi
  leal -1(%rax), %ebx
  leal 1(%rax), %edx
  cmpl $43, %eax
  cmovge %edx, %ebx

  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  movq %rax, %rdi
  movl %ebx, %esi
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  addq $16, %rsp
  xorl %eax, %eax
  popq %rbx
  ret

I separated out the actual calls to Get1 or Get2 you can see that我将对 Get1 或 Get2 的实际调用分开,您可以看到

  • the generated code is identical生成的代码是相同的
  • the compiler is very aggressive at optimizing, there are no function calls etc编译器在优化方面非常积极,没有 function 调用等

Lesson, write your code to be human readable and let the compiler do the heavy lifting课程,将代码编写为人类可读,让编译器完成繁重的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM