std ::对象的对象和const正确性 [英] std::vector of objects and const-correctness

查看:104
本文介绍了std ::对象的对象和const正确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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?

编辑:
Ofc。我不能在operator =()方法中改变this-> c,所以我看不到如何使用operator =()(尽管std :: vector需要)。

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

推荐答案

我不知道为什么没有人说的,但正确的答案是放下 const c $ c> A * 在向量中(使用适当的智能指针)。

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).

你可以给你的类可怕的语义复制调用UB或不做任何事(因此不是一个副本),但为什么所有这些麻烦在UB和坏代码?通过使 const 得到什么? (提示:没有。)你的问题是概念性的:如果一个类有一个const成员,该类是const。对象是const,基本上不能被赋值

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.

只要使它成为非常量私有<不可改变。对于用户,这是等价的,const。它允许隐式生成的函数正常工作。

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.

这篇关于std ::对象的对象和const正确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆