简体   繁体   中英

std::vector of objects and const-correctness

Consider the following:

class A {
public:
    const int c; // must not be modified!

    A(int _c)
    :   c(_c)
    {
        // Nothing here
    }

    A(const A& copy)
    : c(copy.c)
    {
        // Nothing here
    }    
};



int main(int argc, char *argv[])
{
    A foo(1337);

    vector<A> vec;
    vec.push_back(foo); // <-- compile error!
    
    return 0;
}

Obviously, the copy constructor is not enough. What am I missing?

EDIT:
Ofc.I cannot change this->c in operator=() method, so I don't see how operator=() would be used (although required by std::vector ).

I'm not sure why nobody said it, but the correct answer is to drop the const , or store A* 's in the vector (using the appropriate smart pointer).

You can give your class terrible semantics by having "copy" invoke UB or doing nothing (and therefore not being a copy), but why all this trouble dancing around UB and bad code? What do you get by making that const ? (Hint: Nothing.) Your problem is conceptual: If a class has a const member, the class is const. Objects that are const, fundamentally, cannot be assigned.

Just make it a non-const private , and expose its value immutably. To users, this is equivalent, const-wise. It allows the implicitly generated functions to work just fine.

An STL container element must be copy-constructible and assignable 1 (which your class A isn't). You need to overload operator = .

1 : §23.1 says The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignabletypes


EDIT :

Disclaimer : I am not sure whether the following piece of code is 100% safe. If it invokes UB or something please let me know.

A& operator=(const A& assign)
{
    *const_cast<int*> (&c)= assign.c;
    return *this;
}

EDIT 2

I think the above code snippet invokes Undefined Behaviour because trying to cast away the const-ness of a const qualified variable invokes UB .

您缺少一个赋值运算符(或复制赋值运算符),这是三大.

存储类型必须满足 CopyConstructible和 Assignable要求,这意味着也需要 operator=。

Probably the assignment operator . The compiler normally generates a default one for you, but that feature is disabled since your class has non-trivial copy semantics.

I recently ran into the same situation and I used a std::set instead, because its mechanism for adding an element (insert) does not require the = operator (uses the < operator), unlike vector's mechanism (push_back).

If performance is a problem you may try unordered_set or something else similar.

I think the STL implementation of vector functions you are using require an assignment operator (refer Prasoon's quote from the Standard). However as per the quote below, since the assignment operator in your code is implicitly defined (since it is not defined explicitly), your program is ill-formed due to the fact that your class also has a const non static data member.

C++03

$12.8/12 - "An implicitly-declared copy assignment operator is implicitly defined when an object of its class type is assigned a value of its class type or a value of a class type derived from its class type. A program is illformed if the class for which a copy assignment operator is implicitly defined has:

— a nonstatic data member of const type, or

— a nonstatic data member of reference type, or

— a nonstatic data member of class type (or array thereof) with an inaccessible copy assignment operator, or

— a base class with an inaccessible copy assignment operator.

You also need to implement a copy constructor, which will look like this:

class A {
public:
    const int c; // must not be modified!

    A(int _c)
    ...

    A(const A& copy)
    ...  

    A& operator=(const A& rhs)
    {
        int * p_writable_c = const_cast<int *>(&c);
        *p_writable_c = rhs.c;
        return *this;
    }

};

The special const_cast template takes a pointer type and casts it back to a writeable form, for occasions such as this.

It should be noted that const_cast is not always safe to use, see here .

Workaround without const_cast .

A& operator=(const A& right) 
{ 
    if (this == &right) return *this; 
    this->~A();
    new (this) A(right);
    return *this; 
} 

I just want to point out that as of C++11 and later, the original code in the question compiles just fine! No errors at all. However,vec.emplace_back() would be a better call, as it uses "placement new" internally and is therefore more efficient, copy-constructing the object right into the memory at the end of the vector rather than having an additional, intermediate copy.

cppreference states (emphasis added):

std::vector<T,Allocator>::emplace_back

Appends a new element to the end of the container. The element is constructed through std::allocator_traits::construct , which typically uses placement-new to construct the element in-place at the location provided by the container.

Here's a quick demo showing that both vec.push_back() and vec.emplace_back() work just fine now.

Run it here: https://onlinegdb.com/BkFkja6ED .

#include <cstdio>
#include <vector>

class A {
public:
    const int c; // must not be modified!

    A(int _c)
    :   c(_c)
    {
        // Nothing here
    }

    // Copy constructor 
    A(const A& copy)
    : c(copy.c)
    {
        // Nothing here
    }    
};

int main(int argc, char *argv[])
{
    A foo(1337);
    A foo2(999);

    std::vector<A> vec;
    vec.push_back(foo); // works!
    vec.emplace_back(foo2); // also works!
    
    for (size_t i = 0; i < vec.size(); i++)
    {
        printf("vec[%lu].c = %i\n", i, vec[i].c);
    }
    
    return 0;
}

Output:

vec[0].c = 1337
vec[1].c = 999

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM