使用命名对象复制构造函数

Copy constructor with named object

所以这是我的代码:

class A {
int x;
public:
    A(int p) {cout << "constructor\n"; }
    A(const A& p) { cout << "copy constructor\n";}
    A& operator=(const A& p) { cout << "assignment\n"; return *this;}
    ~A() {cout << "destructor\n";}
};  

A foo(){ A temp(3); return temp;}

int main()
{
    A a(1);
    A b = A(2);
    A c = foo();
    //A d = A e(4);   This one doesn't work!
}

我知道匿名对象(未命名对象)具有“表达式范围”,这意味着它们在创建它们的表达式末尾被销毁。这意味着,在我们的代码中,未命名的对象一直存在到分号。

在 12.2/3 中有说明:

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

所以,我知道命名对象和未命名对象在范围上是不同的。

我的问题是为什么最后一行代码不起作用?范围与它有什么关系吗?
还有为什么A c = foo();会起作用,看到右手边也是一个命名对象?

//A d = A e(4);   This one doesn't work!

这只是无效的语法。您不需要 e,甚至在任何地方都没有进一步引用它。

你的陈述应该是这样的

A d = A(4);

A d(4);

初始化需要右侧的表达式。 A e(4) 不是一个表达式,它是一个声明。它没有价值。

您可以使用A d = a; 来调用您的复制构造函数。 这种情况A c = foo();被编译器简化为这种情况A b = A(2);,因为右侧的实体在分配后停止存活,它可以简单地使用右侧而不是左侧。