std::move在将对象推入std::vector push_back时破坏它

std::move destroys my object when I push it to std::vector push_back

本文关键字:std back push move 对象 vector      更新时间:2023-10-16

我做了一个应用程序,遇到了一些麻烦。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超出范围。