Search code examples
c++visual-studio-2012c++11move

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


I have some troubles with an application that I made. std::move destroys your object when you move it to vector pushback. Here a small example:

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

The output will be:

  • Create
  • Move
  • Destroy
  • Test
  • Done!
  • Destroy

How can I make sure that destroy only will be called when FileSetting goes out of scope and not when I move it. I'm trying to avoid pointer.


Solution

  • std::move() doesn't destroy the object. The "Destroy" you're getting is from setting going out of scope.