C++ vector::push_back 使用默认拷贝构造函数

标签 c++ vector copy copy-constructor

我有一个类 (Uniform),它有一个带 2 个参数的构造函数和一个默认的复制构造函数(它只包含 int、 float 、一个 std::vector 和一个 std::map)。我创建了一个

std::vector<Uniform> uniforms

我想用

uniforms.push_back()

行。我使用这段代码来做到这一点(第二行只是在这里测试复制构造函数,因为它目前失败了)

Uniform uni(uniform_name,type);
Uniform uni2=uni;
uniforms.push_back(uni2);

默认构造函数工作正常,“uni2=uni”编译没有问题(因此默认复制构造函数也可以),但 push_back 返回(使用 g++ 作为编译器):

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ext/new_allocator.h:108:9: erreur: no matching function for call to ‘Uniform::Uniform(const Uniform&)’

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ext/new_allocator.h:108:9: note: candidates are:

./inc/uniform.h:16:5: note: Uniform::Uniform(std::string, Uniform_Type)

./inc/uniform.h:16:5: note: candidate expects 2 arguments, 1 provided

./inc/uniform.h:14:7: note: Uniform::Uniform(Uniform&)

./inc/uniform.h:14:7: note: no known conversion for argument 1 from ‘const Uniform’ to ‘Uniform&’

谢谢:)

最佳答案

当您说“默认复制构造函数”(这通常没什么意义)时,我假设您指的是“隐式声明的复制构造函数”或“编译器提供的复制构造函数”

编译器提供的复制构造函数的确切签名将取决于您的 Uniform 类的内容。它可以是 Uniform::Uniform(const Uniform &)Uniform::Uniform(Uniform &) 再次取决于 Uniform 的细节>(您没有提供)。

例如,如果您的 Uniform 包含类型为 T 的子对象(基类或成员),其复制构造函数声明为 T::T(T &)(没有const),那么Uniform的隐式构造函数也会被隐式声明为Uniform::Uniform(Uniform &)(无 const)。

可以在语言标准 (12.8/5) 中找到完整的规范

The implicitly-declared copy constructor for a class X will have the form

X::X(const X&)

if

— each direct or virtual base class B of X has a copy constructor whose first parameter is of type const B& or const volatile B&, and

— for all the nonstatic data members of X that are of a class type M (or array thereof), each such class type has a copy constructor whose first parameter is of type const M& or const volatile M&.

Otherwise, the implicitly declared copy constructor will have the form

X::X(X&)

An implicitly-declared copy constructor is an inline public member of its class.

push_back 实现需要 Uniform::Uniform(const Uniform &),但是你的类中的某些东西导致它成为 Uniform::Uniform(Uniform & )。因此错误。如果没有看到 Uniform 的定义,就无法说出它是什么。

关于C++ vector::push_back 使用默认拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6310638/

相关文章:

c++ - 将虚拟方法放在可复制类型上是否是个好主意?

c++ - 在禁用 MSVC 语言扩展的情况下使用 Boost.Thread header

vector - 为什么 Julia 没有在函数中获取正确的数据?

c++ - 将多态 C++ 对象转换为非多态 C 对象

scala - Scala 库方法 Vector.sorted 使用什么算法?

algorithm - 散列值如何映射到布隆过滤器中的向量?

linux - 如何在csv文件上使用for循环来复制文件

batch-file - 批量复制所有文件而不覆盖

c++ - Visual Studio 无法 'see' 我包含的头文件

c++ - 如何强制 Thrift 只接受来自本地主机的连接