member copying of class

◇◆丶佛笑我妖孽 提交于 2019-12-21 19:56:39

问题


While learning the concept of "copying members", the book gives the following statement.

In addition, a default assignment cannot be generated if a nonstatic member is a reference, a const,or a user-defined type without a copy assignment.

I do not quite understand what does this statement really want to deliver? Or which kind of scenario does this statement refer to? Thanks.


回答1:


This statement has to do with the compiler automatically generating the default assignment operator function for a class you write (i.e. user-defined type). The default assignment works by copying all the members over to a new instance. This statement covers three cases where a default assignment would not be able to be generated:

1) When a member is a reference (i.e. refers to an instance of a variable, like a pointer)

class Foop {
    int& reference;
};

2) When a member variable is constant

class Foople {
    const int someConst;
};

3) When some other class does not have a copy-constructor and you have a member variable of that type, obviously it cannot be copied using the default method (which uses copy-constructors)

class Uncopyable {
private:
    Uncopyable(Uncopyable const& other);
};

class Fleep {
    Uncopyable uncopyable;
};

In these cases, you would need to write your own assignment operator (or possibly do without).




回答2:


If you have a member in your class which is not static (shared between all instances of class), and is either

  1. a reference (high level pointer)
  2. a constant
  3. a user-defined type with dynamic data (the same as the class we're talking about)

The default = operator and copy constructor is no longer valid and you should write manual versions of those.




回答3:


class ClassA
{
    int& _myReferenceMember;
    const int _myConstant;
    ClassB _objWhereClassBHasNoCopyConstructor;
}

Above are examples of the three cases you described. And as you quoted, you must write a custom copy constructor (if you want a copy constructor at all) in such a case, or change your member variables.




回答4:


It refers to the distinction between:

class A { int a; };

and

class B { int& a; };

For class A, the compiler will generate an implicit assignment operator (=), but in the case of B, it cannot. This is because references in C++ don't have pointer semantics. i.e. you cannot change what a reference point to after it is constructed, hence, the implicit copy constructor would not be able to copy that member. The same thing goes for const members (which are explicitly marked as being immutable) and members which don't have a assignment operators (implicit or explicit).

The default assignment operator for A would essentially do this:

class A
{
   A& operator=(A const& a_) { a = a_.a; }
   int a;
};


来源:https://stackoverflow.com/questions/5320675/member-copying-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!