Baz
Baz

Reputation: 13145

const pod and std::vector

To get this code to compile:

std::vector<Foo> factory() 
{
    std::vector<Foo> data;
    return data;
}

I have to define my POD like this:

struct Foo
{
    const int i;
    const int j;

    Foo(const int _i, const int _j): i(_i), j(_j) {}

    Foo(Foo& foo): i(foo.i), j(foo.j){}

    Foo operator=(Foo& foo)
    {
        Foo f(foo.i, foo.j);
        return f;
    }
};

Is this the correct approach for defining a pod where I'm not interested in changing the pod members after creation? Why am I forced to define a copy constructor and overload the assignment operator? Is this compatible for different platform implementations of std::vector? Is it wrong in your opinion to have const PODS like this? Should I just leave them as non-const?

Upvotes: 1

Views: 1542

Answers (2)

Robᵩ
Robᵩ

Reputation: 168716

You ask several questions:

Is this the correct approach for defining a pod where I'm not interested in changing the pod members after creation?

Your question is ill-formed because you are interested in changing the pod members after creation. By using std::vector, you are asking vector::resize(), for example, permission to modify all of the members of your objects via the assignment operator.

Also, as others have pointed out, your operator= doesn't make much sense. It surely doesn't do what you think it does. Specifically, after the expression a=b, the members of a are unchanged.

Why am I forced to define a copy constructor and overload the assignment operator?

Because you are using std::vector. Consider C++2003, §23.1/3, "The type of objects stored in these components must meet the requirements of CopyConstructible types, and the additional requirements of Assignable types."

Practically speaking, it is because vector needs to be able to move your objects around while it does its memory-management.

Is this compatible for different platform implementations of std::vector?

Yes. For any implementation of std::vector, your type must be CopyConstructible and Assignable.

Is it wrong in your opinion to have const PODS like this?

Yes, it contradicts your intended usage. You intend to put them into a vector, where they will be modified.

Should I just leave them as non-const?

Yes. If you leave them as non-const, then you don't need a user-defined copy constructor nor a user-defined assignment operator.

Upvotes: 0

James Kanze
James Kanze

Reputation: 153977

It's undefined behavior to create an std::vector over a type that you can't assign. You can't assign POD's with const members.

Upvotes: 3

Related Questions