std::move在将对象推入std::vector push_back时破坏它
std::move destroys my object when I push it to std::vector push_back
我做了一个应用程序,遇到了一些麻烦。Std::move在将对象移动到vector pushback时破坏它。这里有一个小例子:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class FileSetting
{
private:
FileSetting(FileSetting &fileSetting) { cout << "Copyn"; }
public:
FileSetting(std::string name, void * value, int size) { cout << "Createn"; }
FileSetting(FileSetting &&fileSetting) { cout << "Moven"; }
~FileSetting() { cout << "Destroyn"; }
void test() { cout << "Testn"; }
};
int main()
{
vector<FileSetting> settings;
{
char * test = "test";
FileSetting setting("test", test, strlen(test) * sizeof(char));
settings.push_back(std::move(setting));
}
settings[0].test();
cout << "Done!n";
return 0;
}
输出将是:
- 创建
- 摧毁 测试
- 完成了!
- 摧毁
我如何确保destroy只会在filesset超出作用域时被调用,而不是在我移动它时被调用?我尽量避免使用指针
std::move()
不销毁对象。你得到的"Destroy"是来自setting
超出范围。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- 推导 std::vector::back() 的返回类型
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- 在非空 std::list 上使用 std::list.back<int>() 时"Segmentation Fault"
- 为什么 std::string 的 back() 应该返回对字符的引用?
- 在std::vector中实现back()
- std::vector back()的奇怪行为
- std::vector::back 和 vector::operator[ vector::size() - 1] 之间
- 无法将 std::list 迭代器与 list::back()进行比较?
- 为什么对std::vector::back()的调用会使我的程序崩溃
- 为什么std::array::front和std::array::back不是noexcept
- std::string::back()