You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中`this`指针是否可赋值?为何赋值时CLion提示"Expression is not assignable"?它是否为右值?

Can't Assign to this Pointer in C++? Here's Why

Hey there, let's break down your question clearly:

  • First, the direct answer: You cannot assign to the this pointer in C++—it's not an assignable expression, which is exactly why CLion is throwing that "Expression is not assignable" error. And yes, this is a prvalue (pure rvalue) in C++11 and later standards, which means it can't be the target of an assignment.

Why can't we assign to this?

Let's dig into the details:

  1. The nature of this: When you're inside a non-static member function, this is an implicit reference to the object that called the function. The C++ standard defines this as a prvalue—this kind of value represents a temporary or a value that can't be modified. Assignment operators require a modifiable lvalue (an expression that refers to a writable memory location) on the left side, so this doesn't qualify.
  2. Design intent: The this pointer's job is to point to the current object invoking the member function. Its target is fixed the moment the function starts running—allowing programmers to reassign it would break the core semantics of how member functions interact with objects, leading to unpredictable and buggy code.

What can we do with this?

While you can't reassign this, you can use it in perfectly valid ways:

  • Access or modify members of the current object: this->memberVar = 42;
  • Return the address of the current object from a function:
    class MyClass {
    public:
        MyClass* getCurrentObject() {
            return this; // Totally legal—we're copying the value of `this`, not modifying it
        }
    };
    
  • Pass this as an argument to other functions that expect a pointer to your class type.

Example of invalid vs valid code

Invalid (will trigger the error you saw):

class MyClass {
public:
    void badFunc() {
        MyClass anotherObj;
        this = &anotherObj; // ❌ Error: Can't assign to prvalue `this`
    }
};

Valid:

class MyClass {
private:
    int value;
public:
    void setValue(int val) {
        this->value = val; // ✅ Fine, using `this` to access member
    }
};

内容的提问来源于stack exchange,提问作者Flash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:03:10