使用const成员赋值类 [英] assignment of class with const member

查看:184
本文介绍了使用const成员赋值类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  struct s 
{
const int id;

s(int _id):
id(_id)
{}
};
// ...
矢量< s> v; v.push_back(s(1));



我得到一个编译器错误,'const int id'不能使用默认赋值运算符。



Q1。为什么push_back()需要赋值运算符?

A1。因为目前的c ++标准是这么说的。



Q2。我应该怎么办?




  • 我不想放弃const说明符




  • A2。我将使用智能指针。



    Q3。我想出了一个解决方案,这似乎相当疯狂:

      s& operator =(const s& m)
    {
    if(this ==& m)return * this;
    this->〜s();
    return * new(this)s(m);
    }

    我应该避免这个,为什么? 如果对象位于堆栈上,可以安全使用展示位置新功能。

    解决方案

    C ++ 03要求存储在容器中的元素 CopyConstructible 可分配(见第23.1节)。因此,实现可以决定使用拷贝构造和赋值,因为它们认为合适。这些约束在C ++ 11中放宽。显然, push_back 操作要求是类型为 CopyInsertable 到向量中(见第23.2.3节序列容器)



    此外,C ++ 11容器可以在插入操作中使用移动语义,并执行。


    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?

    解决方案

    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.

    这篇关于使用const成员赋值类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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