使用 const 成员分配类 [英] assignment of class with const member

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

问题描述

考虑以下代码:

struct s
{
    const int id;

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

我收到一个编译器错误,提示const int id"不能使用默认赋值运算符.

I get a compiler error that 'const int id' cannot use default assignment operator.

<罢工>Q1.为什么 push_back() 需要赋值运算符?
A1.因为当前的 C++ 标准是这样说的.

Q1. Why does push_back() need an assignment operator?
A1. Because the current c++ standard says so.

<罢工>Q2.我该怎么办?

Q2. What should I do?

  • 我不想放弃 const 说明符
  • 我想复制数据

A2.我将使用智能指针.

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 要求存储在容器中的元素是 CopyConstructibleAssignable(参见 §23.1).因此,实现可以决定使用他们认为合适的复制构造和赋值.这些约束在 C++11 中放宽了.明确地,push_back 操作要求类型是 CopyInsertable 到向量中(参见 §23.2.3 Sequence Containers)

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)

此外,C++11 容器可以在插入操作中使用移动语义并继续操作.

Furthermore, C++11 containers can use move semantics in insertion operations and do on.

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

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