如果在C++ setter中使用它是否重要?

Elp*_*rto 8 c++ setter this

假设我有一个带有私有变量x的c ++类.对于它的制定者,使用有什么区别this吗?是否有可能出现意外/意外行为this?我不使用?

二传手:

void setX(double input)
{
   x = input;
}
Run Code Online (Sandbox Code Playgroud)

二传手使用this:

void setX(double x)
{
   this->x = x;
}
Run Code Online (Sandbox Code Playgroud)

bdo*_*lan 5

这两个代码片段(假设它们是内联成员函数,因为没有ClassName::位)完全相同.使用您喜欢的任何一种.我倾向于建议不要将命名参数与成员变量相同; 它太容易混淆了.

  • @John:函数范围后面跟着小写字母时没有.`_MethodArg`不能用作参数名,但`_methodArg`可以. (5认同)

Seb*_*ach 4

由于类模板的两阶段查找,this可能需要

  1. 明确说明您指的是会员
  2. 由于查找规则,编译器可能会假设另一个可见的实体意味着

(参见第一个示例)两者是等效的。

在非模板情况下,您通常避免使用this; 生成的代码将是相同的,因此不会有任何差异(参见第二个示例)。原因是编译器将尝试查找它看到的每个符号。第一个查找位置是类范围(块和函数范围除外)。如果它在那里找到该名称的符号,它将this隐式发出。实际上,成员函数只是带有不可见参数的普通函数。

class Foo {
    void foo () { x = 0; }
    void bar () const { std::cout << x; }
    void frob();
    int x;
};
void Foo::frob() {}
Run Code Online (Sandbox Code Playgroud)

实际上转化为

class Foo {        
    int x;
};
inline void foo (Foo *const this) { this->x = 0; }
inline void bar (Foo const * const this) { std::cout << this->x; }
void frob (Foo * const this) {}
Run Code Online (Sandbox Code Playgroud)

由编译器。


模板中的行为示例this

#include <iostream>

void foo() {
    std::cout << "::foo()\n";
}

template <typename>
struct Base {
    void foo() const { std::cout << "Base<T>::foo()\n"; }
};

template <typename T>
struct Derived_using_this : Base<Derived_using_this<T> > {
    void bar() const { this->foo(); }
};

template <typename T>
struct Derived_not_using_this : Base<Derived_not_using_this<T> > {
    void bar() const { foo(); }
};


int main () {
    Derived_not_using_this<void>().bar();
    Derived_using_this<void>().bar();
}
Run Code Online (Sandbox Code Playgroud)

输出:

::foo()
Base<T>::foo()
Run Code Online (Sandbox Code Playgroud)

非模板装配示例:

this

pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp
movq    %rdi, -8(%rbp)
movq    -8(%rbp), %rax
movl    (%rax), %eax
movl    %eax, %esi
movl    $.LC0, %edi
movl    $0, %eax
call    printf
leave
ret
Run Code Online (Sandbox Code Playgroud)

没有this

pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp
movq    %rdi, -8(%rbp)
movq    -8(%rbp), %rax
movl    (%rax), %eax
movl    %eax, %esi
movl    $.LC0, %edi
movl    $0, %eax
call    printf
leave
ret
Run Code Online (Sandbox Code Playgroud)

验证自己:

测试抄送:

#include <stdio.h> // Don't use this. I just did so for nicer assembly.

class Foo {
public:
    Foo () : i(0) {}

    void with_this() const { printf ("%d", this->i); }
    void without_this() const { printf ("%d", i); }
private:
    int i;
};


int main () {
    Foo f;
    f.with_this();
    f.without_this();
}
Run Code Online (Sandbox Code Playgroud)

跑步g++ -S test.cc。您将看到一个名为 的文件test.s,您可以在其中搜索函数名称。