gpt4 book ai didi

c++ - std::vector 是否将其值类型的赋值运算符用于 push_back 元素?

转载 作者:可可西里 更新时间:2023-11-01 15:05:09 25 4
gpt4 key购买 nike

如果是,为什么?为什么不使用值类型的拷贝构造函数?

我收到以下错误:

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc: In member functio
n `ClassWithoutAss& ClassWithoutAss::operator=(const ClassWithoutAss&)':
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: instantiate
d from `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterato
r<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp =
ClassWithoutAss, _Alloc = std::allocator<ClassWithoutAss>]'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_vector.h:564: instantia
ted from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Class
WithoutAss, _Alloc = std::allocator<ClassWithoutAss>]'
main.cpp:13: instantiated from here
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/vector.tcc:238: error: non-st
atic const member `const int ClassWithoutAss::mem', can't use default assignment
operator

在以下代码上运行 g++ main.cpp:

/*
* ClassWithoutAss.h
*
*/

#ifndef CLASSWITHOUTASS_H_
#define CLASSWITHOUTASS_H_

class ClassWithoutAss
{

public:
const int mem;
ClassWithoutAss(int mem):mem(mem){}
ClassWithoutAss(const ClassWithoutAss& tobeCopied):mem(tobeCopied.mem){}
~ClassWithoutAss(){}

};

#endif /* CLASSWITHOUTASS_H_ */

/*
* main.cpp
*
*/

#include "ClassWithoutAss.h"
#include <vector>

int main()
{
std::vector<ClassWithoutAss> vec;
ClassWithoutAss classWithoutAss(1);
(vec.push_back)(classWithoutAss);

return 0;
}

最佳答案

C++03 标准规定元素必须是可复制构造和可复制赋值的,才能在标准容器中使用。因此,实现可以自由使用任何它想要的。

在 C++0x 中,这些要求以每个操作为基础。 (一般来说,元素必须是可移动构造和可移动赋值的。)

要得到你想要的东西,你应该使用像 shared_ptr 这样的智能指针(来自 Boost、TR1 或 C++0x),并完全禁用复制能力:

class ClassWithoutAss
{
public:
const int mem;

ClassWithoutAss(int mem):mem(mem){}
// don't explicitly declare empty destructors

private:
ClassWithoutAss(const ClassWithoutAss&); // not defined
ClassWithoutAss& operator=(const ClassWithoutAss&); // not defined
};

typedef shared_ptr<ClassWithoutAss> ptr_type;

std::vector<ptr_type> vec;
vec.push_back(ptr_type(new ClassWithoutAss(1)));

指针可以很好地复制,智能指针确保您不会泄漏。在 C++0x 中,您可以利用移动语义利用 std::unique_ptr 做到这一点。 (您实际上不需要共享语义,但在 C++03 中它是最简单的。)

关于c++ - std::vector 是否将其值类型的赋值运算符用于 push_back 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3272708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com