Dave Dave - 6 months ago 38
C++ Question

assignment of class with const member

Consider the following code:

struct s
const int id;

s(int _id):
// ...
vector<s> v; v.push_back(s(1));

I get a compiler error that 'const int id' cannot use default assignment operator.

Q1. Why does push_back() need an assignment operator?

A1. Because the current c++ standard says so.

Q2. What should I do?

  • I don't want to give up the const specifier

  • I want the data to be copied

A2. I will use smart pointers.

Q3. I came up with a "solution", which seems rather insane:

s& operator =(const s& m)
if(this == &m) return *this;
return *new(this) s(m);

Should I avoid this, and why (if so)? Is it safe to use placement new if the object is on the stack?

Answer Source

C++03 requires that elements stored in containers be CopyConstructible and Assignable (see §23.1). So implementations can decide to use copy construction and assignment as they see fit. These constraints are relaxed in C++11. Explicitly, the push_back operation requirement is that the type be CopyInsertable into the vector (see §23.2.3 Sequence Containers)

Furthermore, C++11 containers can use move semantics in insertion operations and do on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download