eug*_*ene 29 c++ constructor copy variable-assignment
可能重复:
如何在复制控制功能中处理C数组成员?
我想如果成员变量被声明为指针,隐式复制构造函数(由编译器生成)将复制指针.
我不确定数组成员变量会发生什么.
隐式复制构造函数是否正确复制数组成员?赋值运算符怎么样?
例如:
char mCharArray[100];
int mIntArray[100];
Run Code Online (Sandbox Code Playgroud)
是否可以正确复制mCharArray mIntArray?
小智 57
是的,答案是肯定的.C中的结构也是如此.
typedef struct {
int a[100];
} S;
S s1;
s1.a[0] = 42;
S s2;
s2 = s1; // array copied
Run Code Online (Sandbox Code Playgroud)
只是为了尽可能清楚:
struct X
{
char data_[100];
};
X a, b;
a.data_[10] = 'x';
b = a;
// here, b.data_[n] == a.data_[n] for 0 <= n < 100, so b.data_[10] == 'x'
Run Code Online (Sandbox Code Playgroud)
但是,可能令人讨厌的情况是指针和引用:
struct X
{
char* data_[100];
};
X a, b;
a.data_[10] = new char[6]; // a character array on the heap
strcpy(a.data_[10], "hello"); // put some text into it...
b = a;
// here, b.data_[n] == a.data_[n] for 0 <= n < 100
// so b.data_[10] == a.data_[10] == same character array containing "hello"
// BUT...
b.data_[10][2] = 'L'; // change text to "heLlo" via b.data_[10] pointer...
// here, a.data_[10][2] will be 'L' too, as a.data_[10] and b.data_[10] both point
// to the same underlying heap memory returned by new above...
delete[] a.data_[10]; // ok...
std::cout << b.data_[10]; // NOT ok - this memory's been deallocated!
delete[] b.data_[10]; // NOT ok - this memory's (already) been deallocated!
Run Code Online (Sandbox Code Playgroud)
希望这有助于说明问题.
考虑一种使结构更"安全"的方法:
struct X
{
X(const X& rhs)
{
for (int i = 0; i < 100; ++i)
if (rhs.data_[i])
{
// deep copy of pointed-to text...
data_[i] = new char[strlen(rhs.data_[i]) + 1];
strcpy(data_[i], rhs.data_[i]);
}
else
data_[i] = NULL;
}
char* data_[100];
};
Run Code Online (Sandbox Code Playgroud)
这里,复制构造函数X b = a更安全,更直观,因为它自己创建了所有字符串数据的副本,并且没有对复制X对象的进一步依赖或连接,但这样做速度较慢,可能更浪费内存.
| 归档时间: |
|
| 查看次数: |
31088 次 |
| 最近记录: |