相关疑难解决方法(0)

为什么在这种情况下不调用赋值运算符而支持复制构造函数?

从复制构造函数的维基百科页面:

X a = X();     

// valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me)
// because the second wants a non-const X&
// to create a, the compiler first creates a temporary by invoking the default constructor
// of X, then uses the copy constructor to initialize as a copy of that temporary. 
// For some compilers both versions actually work but this behaviour should not be relied 
// upon because it's non-standard.
Run Code Online (Sandbox Code Playgroud)

特别是部分:

"编译器首先通过调用X的默认构造函数创建一个临时文件,然后使用复制构造函数初始化为该临时文件的副本."

我的问题是(假设这是正确的)为什么会这样?从代码中,我猜想编译器在构造X之后会使用赋值运算符.

我猜它是因为赋值发生在与初始化相同的表达式中? …

c++ oop

2
推荐指数
1
解决办法
1216
查看次数

标签 统计

c++ ×1

oop ×1