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
thispointer in C++—it's not an assignable expression, which is exactly why CLion is throwing that "Expression is not assignable" error. And yes,thisis 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:
- The nature of
this: When you're inside a non-static member function,thisis an implicit reference to the object that called the function. The C++ standard definesthisas 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, sothisdoesn't qualify. - Design intent: The
thispointer'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
thisas 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
相关产品推荐
相关产品推荐

