为什么不能将一个const对象放入STL容器? [英] Why can't you put a const object into a STL container?

查看:324
本文介绍了为什么不能将一个const对象放入STL容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的代码 - 我想把一个const对象放入一个向量。我知道答案是STL容器需要对象可分配和复制构造,但是,没有引用标准,任何人都可以解释什么问题这样做是什么?我不明白为什么这样的类不能被复制(除了c ++不允许它)。

See the code below - I am trying to put a const object into a vector. I know the answer is "STL containers require objects to be assignable and copy constructable", but, without citing the standard, can anyone explain what the problem with doing this is? I don't understand why a class like this could not be copied (besides that c++ doesn't allow it).

它是一个存储的值不是允许改变 - 为什么不能把它放在向量中只是简单地创建另一个对象?

All it is is a value stored that is not allowed to be changed - why can't putting it in a vector simply create another one of these objects?

#include <vector>

// Attempt 1
// /home/doriad/Test/Test.cxx:3:8: error: non-static const member ‘const int MyClass::x’, can’t use default assignment operator

// struct MyClass
// {
//   int const x;
//   MyClass(int x): x(x) {}
// };
// 
// int main()
// {
//   std::vector<MyClass> vec;
//   vec.push_back(MyClass(3));
//   return 0;
// }

// Attempt 2
// /home/doriad/Test/Test.cxx:28:23: error: assignment of read-only member ‘MyClass::x’
struct MyClass
{
  int const x;
  MyClass(int x): x(x) {}
  MyClass& operator= (const MyClass& other)
  {
    if (this != &other)
    {
      this->x = other.x;
    }

    return *this;
  }
};

int main()
{
  std::vector<MyClass> vec;
  vec.push_back(MyClass(3));
  return 0;
}

编辑:

可以使用std :: set和std :: list来做到这一点。我想它是sort()函数在std :: vector使用赋值。这不是UB对吗?

It is possible to do this with std::set and std::list. I guess it is the sort() function in std::vector that uses assignment. This is not UB right?

#include <set>

// Attempt 1
struct MyClass
{
  int const x;
  MyClass(int x): x(x) {}
  bool operator< (const MyClass &other) const;
};

bool MyClass::operator<(const MyClass &other) const
{
  if(this->x < other.x)
  {
    return true;
  }
  else if (other.x < this->x)
  {
    return false;
  }

}


int main()
{
  std::set<MyClass> container;
  container.insert(MyClass(3));
  return 0;
}


推荐答案

EDIT2:的不必工作)C ++ 11标准规定插入方法为向量 deque (以及 push_back 的默认实现)要求值类型为 CopyAssignable ,即值支持:

(Removing a bunch of stuff that doesn't have to work) The C++11 standard states that the insert method for vector and deque (and the default implementation of push_back for that matter) requires the value type to be CopyAssignable, i.e., the value supports:

t= v;

const 的类和结构 CopyAssignable 默认情况下,所以你想要做的不会工作。

Classes and structs with const members are not CopyAssignable by default, so what you want to do won't work.

此文档(n3173)有各种容器要求的说明。

This doc (n3173) has an explanation for the various container requirements.

这篇关于为什么不能将一个const对象放入STL容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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