harttle.github.io icon indicating copy to clipboard operation
harttle.github.io copied to clipboard

2015/07/23/effective-cpp-5

Open harttle opened this issue 7 years ago • 7 comments

Item 5:那些被c++默默地声明和调用的函数 - Effective C++笔记

http://harttle.land/2015/07/23/effective-cpp-5.html

harttle avatar May 02 '18 18:05 harttle

这个貌似问题多多啊,第一段代码里面如果为了阻止编译器合成默认的那几个函数,按你代码的意思,应该是private,或者使用=delete。
最后一段代码里面编译不通过跟引用并没关系吧,合成的拷贝赋值运算符并不会跟成员name有任何关系

By blueyi 2016-05-04T12:48:49Z

harttle avatar May 02 '18 18:05 harttle

类声明中存在引用成员时,拷贝赋值函数会被隐式地禁止掉(至少在g++ 5.1.0中存在这样的行为):

error: object of type 'Person' cannot be assigned because its copy assignment operator is implicitly deleted

如果你认为编译不通过是别的原因可以给个示例来讨论~

By Yang Jun 2016-05-04T13:13:05Z

harttle avatar May 02 '18 18:05 harttle

你没有明白我的意思啊,不管你那里面的成员是否为引用,拷贝赋值运算符在这里都不会编译通过的

By blueyi 2016-05-04T14:07:43Z

harttle avatar May 02 '18 18:05 harttle

不是引用的话显然会编译通过啊 :(

By Yang Jun 2016-05-04T14:30:33Z

harttle avatar May 02 '18 18:05 harttle

查了查资料,明白了,你是正确的,谢谢。网上有个解释感觉是不是会更贴切:因为引用类型必须在定义时就初始化,所以当创建类对象时,必须在构造函数的初始化列表中对引用类型的成员进行直接初始化,而不能在构造函数中初始化。由于合成的默认构造函数并不能直接对这些引用变量进行直接初始化,所以此时编译器会将合成的默认构造函数都定义为delete,也就并不会合成任何构造函数,要求用户必须显示定义这些构造函数,因此不能使用=运算符。 错误提示也是这个意思
```cpp
error: use of deleted function 'Person& Person::operator=(Person&)'
|| p1 = p2;
|| ^
```
谢谢

By blueyi 2016-05-05T01:45:18Z

harttle avatar May 02 '18 18:05 harttle

note: 'Person &Person::operator =(const Person &)': function was implicitly deleted because 'Person' has a data member 'Person::name' of reference type

ghost avatar Dec 04 '18 02:12 ghost

1>c:\users\enyala\source\repos\about_placement_new\about_placement_new\about_placement_new.cpp(11): note: 'Person &Person::operator =(const Person &)': function was implicitly deleted because 'Person' has a data member 'Person::name' of reference type

阅读标准时间=-=

ghost avatar Dec 04 '18 02:12 ghost