简体   繁体   English

默认分配运算符是否在所有成员上都调用operator =?

[英]Does the default assignment operator call operator= on all members?

And similarly, does the default copy constructor call the copy constructor on all members? 同样,默认副本构造函数是否在所有成员上调用副本构造函数? For example, if a class has a non-POD member like so: 例如,如果一个类具有非POD成员,例如:

class A
{
    std::string str;
};

...will the default compiler-generated copy constructor and assignment operator work correctly? ...默认的编译器生成的副本构造函数和赋值运算符可以正常工作吗? Will they call the string's copy constructor and operator= or will they just make a bitwise copy of member variable str ? 他们会调用字符串的copy构造函数和operator=还是只是对成员变量str进行按位复制?

In other words, does having a std::string member mean this class needs a user-implemented copy constructor and assignment operator? 换句话说,拥有std::string成员是否意味着该类需要用户实现的复制构造函数和赋值运算符?

Yes, the compiler-generated one will work correctly. 是的,编译器生成的代码可以正常工作。

However, if you implement your own and leave them empty, it won't. 但是,如果您实现自己的方法并将其留空,则不会。

If you're not managing memory and all your members provide correct copying/assignment/destruction, you don't need (and shouldn't) implement your own copy constructor/destructor/assignment operator. 如果您不管理内存,并且所有成员都提供正确的复制/分配/销毁,则您不需要(也不应该)实现自己的复制构造函数/析构函数/赋值运算符。

In other words, does having a std::string member mean this class needs a user-implemented copy constructor and assignment operator? 换句话说,拥有std :: string成员是否意味着该类需要用户实现的复制构造函数和赋值运算符?

No, the compiler-generated ones will work perfectly. 不,编译器生成的代码可以完美运行。

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

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