我对c ++的范围和内存管理有疑问。这是我遇到麻烦的情况:

Abc function f()
{
  Abc c;
  return c;
}

Abc d = f();
if(d) cout << "hi";


它会说“嗨”吗?我的意思是...在f()中创建的Abc不是动态的(我们没有编写新的)...但是我们正在返回值,因此我们保留了对该对象的引用。它会有价值吗?或者一旦失去价值就会死亡?

谢谢!

最佳答案

#include <iostream>
using std::cout;
using std::endl;

class Abc
{
    int m_value = 0;
public:
    Abc()
    {
        cout << "Default Constructor" << std::endl;
    }

    Abc(const Abc& _source)
    {
        cout << "Copy Constructor" << std::endl;
        //copy stuff
    }

    Abc& operator=(const Abc& _source)
    {
        cout << "assignment operator" << std::endl;
        if (this == &_source)
            return *this;
        //copy stuff

        return *this;
    }

    Abc(const Abc&& _source)
    {
        cout << "Move Constructor" << std::endl;
        //move stuff
    }

    Abc& operator=(const Abc&& _source)
    {
        cout << "move assignment operator" << std::endl;
        //move stuff
        return *this;
    }

    ~Abc()
    {
        cout << "Destructor"<< std::endl;
    }

    void setValue(int _value)
    {
        m_value = _value;
    }

    int getValue()
    {
        return m_value;
    }
};

Abc f()
{
  Abc c;
  c.setValue(100);
  cout << "c value: " << c.getValue() << endl;
  return c;
}

int main()
{
    Abc d = f();
    cout << "d value: " << d.getValue() << endl;
    d.setValue(200);
    cout << "d value: " << d.getValue() << endl;
}


这是输出:

默认构造函数

c值:100

d值:100

d值:200

析构函数

从这里您可以看到编译器足够聪明,可以重复使用分配的对象,而无需进行任何哑副本(C ++ 98/03,C ++ 11相同的输出)。

与MinGW(GCC 4.7.1)一起编译。

08-06 02:24