c++ - 如何在不调用现有对象的析构函数的情况下在 vector 中添加和初始化对象?

标签 c++

我正在做家庭作业,在我向类(class)添加析构函数时遇到了问题。

来自作业:

The class will have a destructor that displays a message indicating that an object has "gone out of scope".

我已经在我的 rectangle 中实现了这个通过输出到 ofstream 来上课对象:

rectangle::~rectangle()
{
    RectOutput << "Object with length " << length << " and width " << width << " is now out of scope." << std::endl;
}

我遇到的问题是,我将这些对象放入一个 vector 中以便于输出到表格中。在我添加析构函数之前,一切看起来都很好。由于 vector 将其数据复制到新的内部数组并删除旧数组以增加大小的方式,因此在创建对象时多次调用析构函数并输出消息。

这项作业的部分限制是我必须用某些值初始化一些对象。使用 vector 的选择是我自己的。这是对象初始化的代码:

std::vector <rectangle> Rectangles;

//Initialize all of our rectangle objects within our vector
Rectangles.push_back(rectangle());
Rectangles.push_back(rectangle(7.1, 3.2));
Rectangles.push_back(rectangle(6.3));
Rectangles.push_back(rectangle(21.0, 21.0));
Rectangles.push_back(rectangle(Rectangles[1]));

这是由此产生的输出:

Object with length 1 and width 1 is now out of scope.
Object with length 1 and width 1 is now out of scope.
Object with length 7.1 and width 3.2 is now out of scope.
Object with length 1 and width 1 is now out of scope.
Object with length 7.1 and width 3.2 is now out of scope.
Object with length 6.3 and width 1 is now out of scope.
Value of 21 is invalid. Values must be greater than 0.0 and less than or equal to 20.0. Default of 1.0 used.
Value of 21 is invalid. Values must be greater than 0.0 and less than or equal to 20.0. Default of 1.0 used.
Object with length 1 and width 1 is now out of scope.
Object with length 7.1 and width 3.2 is now out of scope.
Object with length 6.3 and width 1 is now out of scope.
Object with length 1 and width 1 is now out of scope.
Object with length 1 and width 1 is now out of scope.
Object with length 7.1 and width 3.2 is now out of scope.
Object with length 6.3 and width 1 is now out of scope.
Object with length 1 and width 1 is now out of scope.
Object with length 7.1 and width 3.2 is now out of scope.

如何在不像这样重复调用析构函数的情况下在 vector 中初始化这些对象?我也尝试从 std::vector <rectangle> Rectangles(5); 开始,但是这实际上似乎调用了我的默认构造函数 5 次,用 5 个默认 rectangle 填充 vector 对象,然后当我添加到它时,会看到相同的效果,除了它正在破坏默认对象。

最佳答案

使用Rectangles.emplace_back()而不是 Rectangles.push_back(),你仍然需要 reserveSam Varshavchik所述

关于c++ - 如何在不调用现有对象的析构函数的情况下在 vector 中添加和初始化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835779/

相关文章:

C++ 访问私有(private) vector 值

c++ - 使用 QString 作为 std::unordered_map 中的键

c++ - 如何在鼠标按下事件上显示 QToolTip 并使其弹出一段时间? Qt

c++ - 错误 : major format is 0 (libsndfile, Qt)

c++ - 并行化广度优先搜索

c++ - 可变参数模板扩展 - 扩展除第 i 个条目之外的所有条目

android - 在 JNI 共享库中查找函数?

c++ - 为什么 'const' 在这两种情况下表现不同?

c++ - 无法在 Windows 对话框上显示其他 unicode 东亚语言

c++ - basic_string 专有分配器