【发布时间】:2014-12-14 10:57:27
【问题描述】:
我得到了以下代码块:
#include <vector>
#include <iostream>
struct TestStruct {
bool wasCreated;
TestStruct() {
std::cout << "Default Constructor" << std::endl;
wasCreated = false;
}
~TestStruct() {
if (wasCreated) {
DoImportantStuff();
}
}
void Create() {
wasCreated = true;
}
// delete all copy stuff
TestStruct(const TestStruct&) = delete;
TestStruct& operator=(const TestStruct&) = delete;
// implement only move assignment & ctor
TestStruct(TestStruct&& other) {
std::swap(wasCreated, other.wasCreated);
}
TestStruct& operator=(TestStruct&& other) {
std::swap(wasCreated, other.wasCreated);
return *this;
}
// very important stuff
void DoImportantStuff() {
std::cout << "Do Important Stuff" << std::endl;
}
};
int main() {
std::vector<TestStruct> testVector;
testVector.emplace_back(TestStruct());
testVector.emplace_back(TestStruct());
std::cin.get();
}
这段代码导致输出:
默认构造函数
做重要的事情
默认构造函数
做重要的事情
做重要的事情
基本上我想写一个类,它拥有内存,但只有在我调用Create() 时才分配这个内存。为了避免内存泄漏并避免删除未分配的内存,我引入了wasCreated,这只有在我调用Create() 时才会成立。每个 TestStruct 都应该保存在一个向量中。因此,在实施移动分配和 ctor 并删除了复制分配和 ctor。
现在在我看来,向量在分配新内存时不会调用我的 TestStruct 的默认构造函数。为什么会这样以及如何让向量在内存分配上调用默认构造函数?我需要自己的分配器吗?
【问题讨论】:
-
请使用有效的入口点之一。
void main()不是其中之一。 -
-1 用于
void main。不要那样做。 -
@Cheersandhth.-Alf +1 反击。
void main不会使问题变得或多或少有用。 -
@immibis:
void main向没有思想的读者教授void main。我会说你符合要求。是的,这确实使问题变得不那么有用了。 -
@Cheersandhth.-Alf 我同意不使用
void main()的说法,我不同意-1。代码当然有错误;这就是OP在这里的原因-学习。这个问题本身问得很好,有一个独立的代码示例,实际结果,预期结果,显示了努力 - 简而言之,这是一个在我看来不值得反对的好问题。
标签: c++ vector stl allocation