ruipacheco
ruipacheco

Reputation: 16442

Moving element from container does not empty container?

Given the following code:

#include <vector>
#include <iostream>

struct number {
    int n{666};
};


int main()
{
    std::vector<number> vec;
    std::cerr << vec.size() << std::endl;
    number n;
    vec.push_back(n);
    std::cerr << vec.size() << std::endl;
    auto b = std::move(vec.front());
    std::cerr << "b: " << b.n << std::endl;
    std::cerr << vec.size() << std::endl;
}

I get the following output:

0
1
b: 666
1

Shouldn't the last 1 be 0?

Upvotes: 1

Views: 58

Answers (2)

code_fodder
code_fodder

Reputation: 16371

Once you have used the value at the front and you want to get rid of it you will need to erase it from the vector. I won't talk about the front() returning a ref as 0x5453 mentioned that. But there is no reason to use std::move there - all that does is cast the value to a rvalue reference it does not actually "move" anything on its own.

#include <vector>
#include <iostream>

struct number {
    int n{666};
};

int main()
{
    std::vector<number> vec;
    std::cerr << vec.size() << std::endl;
    number n;
    vec.push_back(n);
    std::cerr << vec.size() << std::endl;

    // Since this is a ref, and your struct is simple - just copy
    auto b {vec.front()};
    // Now remove the element
    vec.erase(vec.begin());

    std::cerr << "b: " << b.n << std::endl;
    std::cerr << vec.size() << std::endl;
}

Upvotes: 1

0x5453
0x5453

Reputation: 13589

std::move doesn't even know that the thing it moved was in a container. The block of memory that the vector owns is still there, just in an unspecified state. It's up to you to manage the vector.

Upvotes: 3

Related Questions