【问题标题】:std::move destroys my object when I push it to std::vector push_back当我将对象推送到 std::vector push_back 时,std::move 会破坏我的对象
【发布时间】:2013-06-15 17:37:11
【问题描述】:

我制作的应用程序遇到了一些问题。当您将对象移动到矢量后推时,std::move 会破坏您的对象。这里是一个小例子:

#include <string>
#include <iostream>
#include <vector>

using namespace std;

class FileSetting
{
private:
    FileSetting(FileSetting &fileSetting) { cout << "Copy\n"; }
public:
    FileSetting(std::string name, void * value, int size) { cout << "Create\n"; }
    FileSetting(FileSetting &&fileSetting) { cout << "Move\n"; }
    ~FileSetting() { cout << "Destroy\n"; }

    void test() { cout << "Test\n"; }
};

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;
}

输出将是:

  • 创建
  • 移动
  • 销毁
  • 测试
  • 完成!
  • 销毁

如何确保仅在 FileSetting 超出范围时调用destroy 而不是在我移动它时调用。我试图避免指针。

【问题讨论】:

    标签: c++ visual-studio-2012 c++11 move


    【解决方案1】:

    std::move() 不会破坏对象。您得到的“破坏”来自setting,超出范围。

    【讨论】:

    • 但是我把设置移到了向量上。所以移动不是真正的移动吗?有没有办法避免破坏设置?
    • @Ordo “移动”一个对象不会神奇地将它从堆栈中传输出来。该对象仍然存在。只是移动可以让您从对象中“窃取”大量资源。移动操作(ctor、赋值操作)仍必须使对象处于有效状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多