C++未命名对象调用成员函数的行为及后续访问疑问
C++临时对象调用成员函数的行为解析
核心问题解答
1. 这是栈上创建的临时对象吗?
是的。Student("Goofupp", 27, 1001)会在栈内存中创建一个Student类型的临时对象,调用对应构造函数完成初始化。这个临时对象的生命周期极短——仅在包含它的完整表达式执行期间存在,也就是getInfo()成员函数调用完成后,该临时对象会被自动销毁,对应的栈内存也会被释放。
2. 后续代码能否访问该对象?
完全不可行。这个临时对象没有绑定到任何命名变量(比如代码里的rahul),也没有通过const引用等操作延长生命周期。表达式执行完毕后,对象就被销毁、内存被回收,没有任何标识符能指向它,自然无法在后续代码中访问。
3. 为什么不像int;那样触发报错?
两者语法本质完全不同:
int;是无效的声明语句,只指定了类型但未定义任何实体(变量或对象),违反C++声明规则,因此编译器会报"declaration does not define anything"类错误。Student("Goofupp", 27, 1001).getInfo()是合法的表达式语句:Student(...)是创建临时对象的表达式,紧接着调用其成员函数getInfo(),整个语句符合C++"表达式加分号构成语句"的语法规则,编译器会正常处理。
代码示例
可正常执行的代码
#include <iostream> #include <string> class Person { public: std::string name; int age; Person(std::string n, int a) : name(n), age(a) {} void getInfo() { std::cout << "Name : " << name << std::endl; std::cout << "Age : " << age << std::endl; } }; class Student : public Person { public: int rollNo; Student(std::string n, int a, int r) : Person(n, a), rollNo(r) {} void getInfo() { std::cout << "Name : " << name << std::endl; std::cout << "Age : " << age << std::endl; std::cout << "Roll No : " << rollNo << std::endl; } }; int main(int argc, const char* argv[]) { Student("Goofupp", 27, 1001).getInfo(); // 创建临时对象并调用成员函数 Student rahul("Rahul", 23, 1002); // 创建命名对象 rahul.getInfo(); return 0; }
报错的对比代码
#include <iostream> using namespace std; int main() { int; // 无效声明,仅指定类型未定义实体 cout<<"hello\n"; return 0; }
内容的提问来源于stack exchange,提问作者P N Singh
相关产品推荐
相关产品推荐

