const对象的复制构造函数

copy constructor for const object

本文关键字:构造函数 复制 对象 const      更新时间:2023-10-16

我有一个以下类foo

class foo
{
    int *arr; // arr holds numbers
    int sz; // size of array
    public:
    // Suppose I have made default and 1 parameter c'tor
    foo(const foo &f)
    {
        sz = f.sz;
        arr = new int[sz];
        for(int i=0;i<sz;i++)
            arr[i]=f.arr[i];
    }
};
int main()
{
    foo x(5); //5 is size of array
    const foo y = x; //doesn't work as I haven't initialized in member-initialization list, but how to write for loop in member initialization list ?
}  

那么如何在成员初始化列表中写入循环?

在这种情况下,您可以使用std::vector

通常,我将创建一个私有静态方法,该方法将执行分配并复制。然后可以使用初始化列表:

static int* CloneInts(const foo& f) {
    int* ints = new ...
    ...copy them from @a f.arr...
    return ints;
}

然后您的启动名单看起来像:

foo(const foo& f) : arr(CloneInts(f)), sz(f.sz) {

您是否尝试过直接使用复制构造函数构造它?

const foo y(x);

您应该澄清您的问题,因为问题中的问题实际上并不存在。

const foo y = x;行将编译并与该复制构造函数一起使用。在构造函数完成之前,正在构造的const对象不是" const"。因此,即使要构造的对象为const。

还要注意,示例中的循环甚至都没有修改任何const的任何内容 - 由于数组是动态分配的,这些数组元素即使对象本身没有修改。例如,arr指针在CTOR完成后不可修改,但是arr[0]仍然是。

尝试以下内容以查看两个动作点:

#include <stdio.h>
#include <algorithm>
class foo
{
    int *arr; // arr holds numbers
    int sz; // size of array
    public:
    foo() : arr(0), sz(0) { puts("default ctor");}
    foo(int x) : arr(0), sz(x) {
        puts( "int ctor");
        arr = new int[sz];
        for(int i=0;i<sz;i++)
            arr[i]=0;
    }
    foo(const foo &f)
    {
        puts("copy ctor");
        sz = f.sz;
        arr = new int[sz];
        for(int i=0;i<sz;i++)
            arr[i]=f.arr[i];
    }
    ~foo() {
        delete [] arr;
    }
    foo& operator=(const foo& rhs) {
        if (this != &rhs) {
            foo tmp(rhs);
            std::swap( arr, tmp.arr);
            std::swap( sz, tmp.sz);
        }
        return *this;        
    }
    void update() const {
        for(int i = 0; i < sz; i++) {
            arr[i] = arr[i] + 1;
        }
    }
    void dump() const {
        for(int i = 0; i < sz; i++) {
            printf("%d ", arr[i]);
        }
        puts("");
    }
};
int main()
{
    foo x(5); //5 is size of array
    const foo y = x; 
    y.dump();
    y.update(); // can still modify the int array, even though `y` is const
    y.dump();
}  

我认为您可能会混淆构造const对象与具有const成员的对象的构造对象,因为这些成员必须在初始化列表中初始化。