C++类实例化理论

Dew*_*rld 3 c++ oop

#include <iostream>
using namespace std;

class A {
public:
    A() {
        cout << "Default Ctor" << endl;
    }
};

int main() {
    A(); // <------- Problem

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它在控制台上显示Default Ctor.我的问题

  • 有效吗?
  • 如果是这样,它是如何实例化的,因为我没有使用新的或任何对象?

Luc*_*ore 8

正在创建一个新对象A().

有效吗?

是的.

如果是这样,它是如何实例化的,因为我没有使用新的或任何对象?

new只需在动态内存中创建对象.您正在自动内存中创建对象.另外,仅仅因为你没有给对象命名,并不意味着它没有被创建.

想一想:

int foo() { return 1; }

int main()
{
   foo();
}
Run Code Online (Sandbox Code Playgroud)

抛弃优化foo()实际上是否回归1?是的,它确实.只是你没有使用它.

编辑:

让我们分解一下:

A();  //creates a temporary unnamed object in automatic storage

A a;   //creates an object a of type A in automatic storage

A a(); //creates no object, but declare a function a returning A and taking no parameters

A a(A());   //these two are equivalent
A a = A();  //creates a temporary unnamed object and creates an object a in automatic storage
            //using the compiler-generated copy constructor

A a;
a = A();    //creates an object a in automatic storage
            //creates an unnamed temporary object and uses the compiler-generated assignment operator
            //to assign it to a

A a = &A(); //invalid, &A() is the address of a temporary a, which is illegal
Run Code Online (Sandbox Code Playgroud)