assignment of class with const member
Asked Answered
P

7

13

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?

Penury answered 22/7, 2012 at 16:30 Comment(12)
About #1, it's a dynamic array. It's going to have to copy (or move) the elements.Retainer
And because copying does id = old.id it cannot be const.Domingodominguez
&chris That's the part I don't get, it should copy and not assignPenury
You could enable C++11 and the code will compile.Eyeglasses
@KennyTM, Oh, you can move consts? And here I was getting a working sample of a const int * as the member working with it :/ It did work, though :pRetainer
You can copy from const objects but you can't [copy/move] assign to a const object, even in C++11.Heteronomy
For Q3: you must absolutely check for self-assignment, and then say this->~s(); before the new call (as it is UB to overwrite the memory of an object whose destructor is non-trivial)... but I'm not sure if you're allowed to destroy an object inside its own member function.Novikoff
If you want your data member to be copied during copy assignment it doesn't make any sense to declare it const. Why do you want it to be const or why don't you want to give up the const?Heteronomy
Q3 answeredAmontillado
@KerrekSB "as it is UB to overwrite the memory of an object whose destructor is non-trivial" why?Tipster
@curiousguy: I phrased that badly. It's not always UB; it's UB if the program depends on the side effects of the destructor (by [basic.life]).Novikoff
What does *new(this) s(m) mean?Umbrage
U
5

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.

Univalve answered 22/7, 2012 at 16:49 Comment(2)
Move assignment is no better than copy assignment when it comes to const members (i.e. it's disabled as well).Divisionism
@LucDanton right, but there is no longer the requirement that the type be assignable.Univalve
A
5
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.

Amontillado answered 24/11, 2017 at 14:44 Comment(1)
For an indepth case study, see [basic.life]/8 ans this answer about it.Amontillado
H
4

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.

Hunchbacked answered 22/7, 2012 at 17:6 Comment(6)
Why is this undefined behavior?Tahitian
related question: #47474121 why is it UB?Amontillado
And it may not be.Amontillado
It is undefined behavior, as the compiler assumes, that const members are constant - even during an assignment to the whole object. So after the placement new trick, the compiler might still use the old value of that const field, if it had been loaded into a register, for example. So UB. std::launder() is a way around it, but I do not recommend it. Make that const field private instead and use a getter function to allow its value to be read.Cardioid
@KaiPetzke This was true up until c++ when basic.life replacement removed the restriction against const subobjects. See open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1971r0.html#RU007Coleen
Wrapping the class in a pointer class allows copy assignment.Autolycus
B
3

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.

Bulk answered 24/11, 2017 at 17:35 Comment(0)
L
2

Q2. What should I do?

Store pointers, preferably smart.

vector<unique_ptr<s>> v;
v.emplace_back(new s(1));
Lhasa answered 22/7, 2012 at 17:3 Comment(0)
Y
0

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.

Yocum answered 22/7, 2012 at 17:10 Comment(0)
M
-3

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;
}
Mould answered 21/2, 2013 at 16:5 Comment(1)
I’m not 100% sure, but I’m pretty much afraid this may invoke UBGeminius

© 2022 - 2024 — McMap. All rights reserved.