assignment of class with const member

2019-02-16 22:02发布

问题:

Consider the following code:

struct s
{
    const int id;

    s(int _id):
        id(_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;
    this->~s();
    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?

回答1:

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.



回答2:

I don't want to give up the const specifier

Well, you have no choice.

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

Undefined behaviour.

There's a reason why pretty much nobody uses const member variables, and it's because of this. There's nothing you can do about it. const member variables simply cannot be used in types you want to be assignable. Those types are immutable, and that's it, and your implementation of vector requires mutability.



回答3:

s& operator =(const s& m)
{
    if(this == &m) return *this;
    this->~s();
    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?

You should avoid it if you can, not because it is ill-formed, but because it is quite hard for a reader to understand your goal and trust in this code. As a programmer, you should aim to reduce the number of WTF/line of code you write.

But, it is legal. According to

[new.delete.placement]/3

void* operator new(std::size_t size, void* ptr) noexcept;

3 Remarks: Intentionally performs no other action.

Invoking the placement new does not allocate or deallocate memory, and is equivalent to manually call the copy constructor of s, which according to [basic.life]/8 is legal if s has a trivial destructor.



回答4:

Q2. What should I do?

Store pointers, preferably smart.

vector<unique_ptr<s>> v;
v.emplace_back(new s(1));


回答5:

Ok,

You should always think about a problem with simple steps.

std::vector<typename T>::push_back(args);   

needs to reserve space in the vector data then assigns(or copy, or move) the value of the parameter to memory of the vector.data()[idx] at that position.

to understand why you cannot use your structure in the member function std::vector::push_back , try this:

std::vector<const int> v; // the compiler will hate you here, 
                          // because this is considered ill formed.

The reason why is ill formed, is that the member functions of the class std::vector could call the assignment operator of its template argument, but in this case it's a constant type parameter "const int" which means it doesn't have an assignment operator ( it's none sense to assign to a const variable!!). the same behavior is observed with a class type that has a const data member. Because the compiler will delete the default assignment operator, expel

struct S
{
    const int _id; // automatically the default assignment operator is 
                   // delete i.e.  S& operator-(const S&) = delete;
};
// ... that's why you cannot do this
std::vector<S> v; 
v.Push_back(S(1234));

But if you want to keep the intent and express it in a well formed code this is how you should do it:

class s
{
    int _id;
public:
    explicit s(const int& id) :
    _id(id)
    {};

    const int& get() const
    {
    return _id; 
    }; // no user can modify the member variable after it's initialization

};
// this is called data encapsulation, basic technique!
// ...
std::vector<S> v ; 
v.push_back(S(1234)); // in place construction

If you want to break the rules and impose an assignable constant class type, then do what the guys suggested above.



回答6:

It's not really a solution, but a workaround:

#include <vector>
struct s
{
  const int id;
  s(int _id):
    id(_id)
    {}
};

int main(){
  std::vector<s*> v;  
  v.push_back(new s(1));
  return 0;
}

This will store pointers of s instead of the object itself. At least it compiles... ;)

edit: you can enhance this with smart c++11 pointers. See Benjamin Lindley's answer.



回答7:

Use a const_cast in the assignment operator:

S& operator=(const S& rhs)
{
    if(this==&rhs) return *this;
    int *pid=const_cast<int*>(&this->id);
    *pid=rhs.id;
    return *this;
}