在 std::vector 中引用对象而不为其创建变量是否会创建该对象的新实例?

Does Referring to an Object without creating a variable for it in a std::vector create a new instance of that object?

我在堆中有一个对象向量,它是我通过

创建的
auto a = std::make_shared<std::vector<MyClass>>();

我通过调用

在该向量中放置了几个 MyClass 实例
a->push_back(MyClass());

根据我的理解,上面的代码在堆栈上创建了一个 MyClass 实例,然后将其复制到堆内存中的 a。

所以此时,向量和对象都在堆内存中。

我的问题是,如果我打电话给

a->at(0).myMethod();

会不会把MyObject复制到栈中,然后调用方法?还是直接调用对象的方法?

std::vector::at returns 对元素的引用,然后直接在元素上调用该方法,这里不会复制临时对象。

Returns a reference to the element at specified location pos, with bounds checking.

To my understanding, the above creates an instance of MyClass on stack, then copies it to a, in heap memory.

不在 C++17 或更高版本中。在此之前,特别允许实现省略副本,在向量的分配中构建。