简体   繁体   English

C++:将空对象分配给现有对象

[英]C++ : Assigning empty object to an existing object

EDIT: fixed up code to clear up some confusion编辑:修复了代码以消除一些混乱

As the title says I am wondering what happens to an object when I assign an empty object to it.正如标题所说,我想知道当我为一个对象分配一个空对象时会发生什么。

Here's a specific example with just the operator overloads and class data members:这是一个仅包含运算符重载和类数据成员的特定示例:

class triangle
{
  vector3d p[3];
  vector2d *uv = nullptr;
 int nChannels = 0;
 public:
void operator=(const triangle &obj)
{
  delete[] uv;
  nChannels= obj.nChannels;
  memcpy(p, obj.p, sizeof(vec3d) * 3);
  uv = new vec2d[3 * obj.nChannels];
  memcpy(uv, obj.uv, 3 * obj.nChannels * sizeof(vec2d));

}

}

int main()
{
 triangle p;
 d = p; // where d is some initialized or uninitialized instance of triangle
 d = p;
}

In short, what happens when I assign an object which has one member that has not been initialized, to another object and what happens when I call new triangle[0], I would expect when I call new triangle[0] to be given a nullptr but I am not so sure anymore.简而言之,当我将具有一个尚未初始化的成员的对象分配给另一个对象时会发生什么,以及当我调用 new triangle[0] 时会发生什么,我希望当我调用 new triangle[0] 时会得到一个nullptr 但我不再那么确定了。

what happens when I assign an object who has one member that has not been initialized当我分配一个具有一个未初始化成员的对象时会发生什么

The assignment operator will be called.赋值运算符将被调用。 In this case, you've provided a user declared assignment operator.在本例中,您提供了一个用户声明的赋值运算符。

The provided operator (like an implicitly generated one) reads the state of the right hand operand, which in this case is default initialised.提供的运算符(类似于隐式生成的运算符)读取右手操作数的状态,在这种情况下,它是默认初始化的。 p lacks an initialiser, so the implicit default constructor leaves it with an indeterminate value. p缺少初始值设定项,因此隐式默认构造函数给它留下一个不确定的值。 The behaviour of reading an indeterminate value is undefined.读取不确定值的行为是未定义的。

That is, if the program could be compiled in the first place.也就是说,如果程序可以首先编译。 It uses undeclared identifiers, and is ill-formed.它使用未声明的标识符,并且格式错误。

and what happens when I call new triangle[0]当我调用new triangle[0]时会发生什么

An array of length 0 would be created.将创建长度为 0 的数组。

would expect when I call new triangle[0] to be given a nullptr期望当我调用 new triangle[0] 时会得到一个 nullptr

Your expectation is misguided.你的期望被误导了。 The resulting pointer would be non-null (unless you used std::nothrow and the allocation failed).结果指针将为非空(除非您使用std::nothrow并且分配失败)。 Indirecting through that pointer would have undefined behaviour.通过该指针间接将具有未定义的行为。 The program would leak memory unless the allocation is released with delete[] .除非使用delete[]释放分配,否则程序会泄漏内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM