构造函数没有被调用

Constructor not getting called

我正在制作一个包含 4 个 std::list 的数组。但是当我尝试访问数组的第一个列表的第一个 A 对象并对其调用 callMe() 方法时,我得到了一个奇怪的输出。

现在可能发生了两件事:

  1. 列表是否为空。
  2. 当我试图访问第一个列表的第一个元素时创建了一个对象 ((*(arrayOflistOfA[0].begin()))).

以上案例详情:

  1. 如果没有创建 A 对象,那么我应该得到一个异常。但是我没有得到任何异常,所以我假设创建了一个 A 对象。
  2. 所以如果确实创建了一个A对象,那么应该已经调用了构造函数。

我错过了什么?

#include <iostream>
using namespace std;
class A {
public:
    A() {
        cout<<"Constructor called"<<endl;
        x=20;
    }
    void callMe();
private:
    int x;
};

void A::callMe() {
    cout<<"Value of x = "<<x<<endl;
}

int main() {
    const int size = 4;
    list<A>* arrayOflistOfA = new list<A>[size];
    (*(arrayOflistOfA[0].begin())).callMe();
}

输出为:

Value of x = 0

但输出应该是:

Constructor called
Value of x = 20

您实际上并未使用任何值填充列表。我测试了以下代码并包含注释说明。

#include <iostream>
#include <list>
using namespace std;
class A {
public:
    A();
    void callMe();
private:
    int x = 0;
};

A::A()
{
    cout << "Constructor called" << endl;
    x = 20;
}

void A::callMe() {
    cout << "Value of x = " << x << endl;
}

int main() {
    const int size = 4;
    list<A>* arrayOflistOfA = new list<A>[size];
    cout << arrayOflistOfA->size() << endl; // As you can see, size is 0 here - you created a list of nulls.

    for (int i = 0; i < size; i++)
    {
        arrayOflistOfA->push_back(A());
    }

    // The below code demonstrates how to loop through the array once it's populated.
    list<A>::iterator it;
    for (auto& a : *arrayOflistOfA)
    {
        a.callMe();
    }
    return 0;
}

我得到了问题的答案。首先,我尝试使用 GNU C++ 编译器在我的 mac 上 运行 这段代码,但是当我在 iPhone 模拟器上 运行 相同的代码时,它崩溃了。所以正如@PaulMcKenzie 提到的,我确实在尝试取消引用一个无效的迭代器。

If no A object was created then I should have got an exception.

不正确。

But I didn't get any exception so I am assuming that an A object was created.

不要假设找出答案。 转至 begin() and for iterators and discover that you do not get an exception, you get UB 的一些文档。

An A object was created when I tried to access the first element of the first list((*(arrayOflistOfA[0].begin()))). [And] if an A object was indeed created, then the constructor should have been called.

没错。很明显,列表中没有任何元素。

我们知道,因为您的程序中没有 adds elements to the list.

的代码

另外你不应该动态分配容器,除非你真的,真的需要(我从来没有发现需要)。