复制构造函数可以采用非const参数吗? [英] Can a copy-constructor take a non-const parameter?

查看:182
本文介绍了复制构造函数可以采用非const参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,有一个函数 foo()如下,

I have this problem, there is a function foo() as follows,

vector<ClassA> vec;

void foo()
{
    ClassA a;   //inside foo, a ClassA object will be created
    a._ptr = new char[10];

    vec.push_back(a);   //and this newly created ClassA object should be put into vec for later use
}

AFAIK, vec 将调用 ClassA 的copy-ctor来复制新创建的对象 a ,这就是问题所在。如果我以通常的方式定义 ClassA 的copy-ctor,

And AFAIK, vec will invoke ClassA's copy-ctor to make a copy of the newly created object a, and here is the problem. If I define ClassA's copy-ctor the usual way,

ClassA::ClassA(const ClassA &ra) : _ptr(0)
{
    _ptr = ra._ptr;
}

然后对象 a 并且它的副本(由vec创建)将具有 _ptr 指向相同区域的指针,当 foo 完成时, a 将调用析构函数以释放 _ptr ,然后释放 a vec 中复制将是一个悬空指针,对吗?由于这个问题,我想以这种方式实现 ClassA 的copy-ctor,

then object a and its copy (created by vec) will have pointers _ptr pointing to the same area, when foo finishes, a will call the destructor to release _ptr, then a's copy in vec will be a dangling pointer, right? Due to this problem, I want to implement ClassA's copy-ctor this way,

ClassA::ClassA(ClassA &ra) : _ptr(0) //take non-const reference as parameter
{
    std::swap(_ptr, a._ptr);
}

我的实现可以吗?还是其他任何方法可以帮助完成这项工作?

Is my implementation ok? Or any other way can help accomplish the job?

推荐答案

要回答您的名义问题:是的,任何 T 具有一个类型为 T& T const& (它可能还包含其他默认参数)是一个副本构造函数。在C ++ 11中,还有一个 move 构造函数,该构造函数需要一个 T&& 类型的参数。

To answer your titular question: Yes, any constructor for a class T that has one mandatory argument of type T & or T const & (it may also have further, defaulted arguments) is a copy constructor. In C++11, there's also a move constructor which requires one argument of type T &&.

拥有一个非恒定拷贝构造函数,该构造函数实际上会改变参数,从而使您的类具有非常不寻常的语义(通常是转移语义),应进行大量记录;它还可以防止您复制常量(显然)。旧的 std :: auto_ptr< T> 正是这样做的。

Having a non-constant copy constructor that actually mutates the argument gives your class very unusual semantics (usually "transfer semantics") and should be extensively documented; it also prevents you from copying something constant (obviously). The old std::auto_ptr<T> does exactly that.

如果可能的话,新的C + +11样式的可变rvalue引用和move构造函数为在原始对象中不再需要资源时移动资源的问题提供了更好的解决方案。这是因为右值引用是对 mutable 对象的引用,但是它只能绑定到安全表达式,例如临时变量或您已明确强制转换的事物(通过 std :: move ),并因此标记为一次性。

If at all possible, the new C++11-style mutable rvalue references and move constructors provide a far better solution for the problem of "moving" resources around when they're no longer needed in the original object. This is because an rvalue reference is a reference to a mutable object, but it can only bind to "safe" expressions such as temporaries or things that you have explicitly cast (via std::move) and thus marked as disposable.

这篇关于复制构造函数可以采用非const参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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