【问题标题】:What wrong with the C++ anonymous object? [duplicate]C++ 匿名对象有什么问题? [复制]
【发布时间】:2014-08-02 13:13:55
【问题描述】:

我写了这样一个简单的代码:

class Test
{
public:
    Test()
    {
        cout << "Constructor called." << endl;
    }

    ~Test()
    {
        cout << "Destructor called." << endl;
    }

    Test(const Test& test)
    {
        cout << "Copy constructor called." << endl;
    }

    void Show() const
    {
        cout << "Show something..." << endl;
    }
};

Test Create()
{
    return Test();
}

int main()
{
    Create().Show();
}

这段代码的输出是:

Constructor called.
Show something...
Destructor called.

但是当我像这样修改函数 Create() 时:

Test Create()
{
    Test test;
    return test;
}

输出是:

Constructor called.
Copy constructor called.
Destructor called.
Show something...
Destructor called.

为什么匿名对象不调用拷贝构造函数和析构函数?请帮帮我,谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

这称为copy elision。在这两种情况下都允许复制省略;由于某种原因,您的编译器在第一种情况下会这样做,但在第二种情况下不会。 (调试模式下的 MSVC 有时显然决定不这样做)。

注意,当您说“匿名类”时,您的意思是 临时对象。 “匿名类”意味着不同的东西。

【讨论】:

  • 有匿名类,只是不是OP想的。
  • @C.R. OP 的代码中没有匿名类。唯一的类有一个名字,Test
猜你喜欢
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2016-09-12
相关资源
最近更新 更多