vendredi 27 novembre 2015

C++ std::move unexpected behaviour (moving string when intended for smart pointer)

When I pass a string literal to a dynamically allocated unique_ptr and then store in vector (using std::move since there's apparently no other way), I get an odd return value when the string is fetched - it appears to have been cut/moved.

#include <iostream>
#include <vector>
#include <memory>

class Something {
private:
    const char* name;
public:
    Something(const char* name) {
        this->name = name;
    }

    void printDetails() {
        std::cout << this->name << std::endl;
    }
};

int main()
{
    std::vector<std::unique_ptr<Something>> stuff;

    for(int i = 0; i < 10; i++) {
        std::unique_ptr<Something> thing(new Something("A nice fun string" + i));
        stuff.push_back(std::move(thing));
    }

    for(uint i = 0; i < stuff.size(); i++) {
        stuff[i]->printDetails();
    }

    return 0;
}

Output:

A nice fun string
 nice fun string
nice fun string
ice fun string
ce fun string
e fun string
 fun string
fun string
un string
n string

Aucun commentaire:

Enregistrer un commentaire