[英]disabling copy constructor in c++ and use of an Object
Using the following code : 使用以下代码:
#include <iostream>
class A
{
public:
A(int truc) : truc(truc) {}
A(const A & other) = delete;
private:
int truc;
};
class B
{
public:
B(int machin, A a) : machin(machin), a(a) {}
private:
int machin;
A a;
};
int main()
{
A a(10);
B b(2,a);
return 0;
}
I get a compile error "error: use of deleted function 'A::A(const A&)" 我得到一个编译错误“错误:使用已删除的函数'A :: A(const A&)”
How can I circonvent this problem if I still want the class A not to be able to be copied ? 如果我仍然希望A类不能被复制,我怎么能解决这个问题呢?
Taking A
by value in B::B(int machin, A a)
is the main issue, do B::B(int machin, A& a)
or B::B(int machin, const A& a)
. 在
B::B(int machin, A a)
取A
的值是主要问题, B::B(int machin, A& a)
或B::B(int machin, const A& a)
。 The same applies to the assignment to the field within the constructor body. 这同样适用于构造函数体内对字段的赋值。 The field declaration in class
B
should hence be A& a;
因此,
B
类的实地宣言应为A& a;
or const A& a;
或
const A& a;
, respectively. , 分别。
However, you probably also want to delete the assignment operator: A& operator=( const A& ) = delete;
但是,您可能还想删除赋值运算符:
A& operator=( const A& ) = delete;
Take a look at boost non-copyable . 看一下不可复制的提升。
Its implementation also depends on whether C++11 is available: http://www.boost.org/doc/libs/1_60_0/boost/core/noncopyable.hpp 它的实现还取决于C ++ 11是否可用: http : //www.boost.org/doc/libs/1_60_0/boost/core/noncopyable.hpp
B
's constructor takes object of type A
by value -> creates new object (copy) B
的构造函数通过值获取类型A
的对象 - >创建新对象(副本)
B(...,A a) ...
^^^^ pass by value
Passing by reference won't create a new object (copy). 通过引用传递不会创建新对象(副本)。
B(...,A &a)...
^^^^^ pass by reference -> no copy
Also, this means that you can't store it in B
as object A a
, because that would, again, create new object (copy), you'll have to store it as reference. 此外,这意味着您不能将其作为对象
A a
存储在B
中,因为这将再次创建新对象(副本),您必须将其存储为引用。
This could cause some problems: 这可能会导致一些问题:
B* createNewObject()
{
A a(...); //local object is created
B* ptr = new B(...,a); // reference in B now refers to local object
}// However, here is local object destroyed, so reference in B is now invalid (dangling reference)
int main()
{
B *pb = createNewObject();
//Any operation on B working with that invalid reference causes UNDEFINED BEHAVIOUR
}
Additionaly, bear in mind that any change in a
will also change object you passed (because that reference refers to same object you passed). Additionaly,请记住,在任何改变
a
也将改变对象是传入(因为引用是指你通过同一个对象)。
Considering the alternative to copying is moving, you want: 考虑到复制的替代方法正在发生变化,您需要:
B(int machin, A&& a) : machin(machin), a(a) {}
That correctly disallows A a(10); B b(2,a);
这正确地不允许
A a(10); B b(2,a);
A a(10); B b(2,a);
which is a copy of a
. 这是一个复制
a
。 You'd now need std::move(a)
there. 你现在需要
std::move(a)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.