Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 5
    You are copying the temporary Car object that you constructed here Car(1). If you want to avoid this copy use emplace_back, e.g. vec.emplace_back(1). emplace_back will call any available constructor and contruct the object being added directly in the vector, without any copying. Commented Mar 29, 2025 at 20:07
  • I'm not sure, but maybe because vector contains Car objects and not pointers or references on Car objects. Because of that, every time you push element into vector, it will make copy of that element and hence call copy constructor. Commented Mar 29, 2025 at 20:07
  • 1
    See std::vector::push_back() and it should be clear that it copies its argument. Commented Mar 29, 2025 at 20:13
  • Btw; this->weight=other.weight; can simply be weight=other.weight;. There's no need to explicitly dereference this. Commented Mar 29, 2025 at 20:15
  • 1
    @JesperJuhl or even just using a member initializer list. Commented Mar 30, 2025 at 0:35