1

返回对象时,我认为返回指针或引用是正确的方法,因为在返回对象时会创建临时对象。

在这个例子中,hello() 函数返回一个类型为 A 的对象,返回值存储在对象 a 中。

A hello()
{
    A a(20); // <-- A object is created in stack
    cout << &a << endl;
    return a; // <-- Temporary object is created for return value
}

void test1()
{
    A a = hello(); // copy constructor is called
    cout << &a << endl;
}

我的期望是应该调用三个构造函数。但是,当我test1()使用 g++ 4.8 执行时,构造函数只被调用一次,而不是 trice。

class A
{
    int x;
public: 
    A() {
        cout << "Default constructor called" << endl;
    }  
    A(const A& rhs) 
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A& operator=(const A& rhs)
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A(int x) : x(x) {
        cout << "*I'm in" << endl;
    }
    ~A() {
        cout << "*I'm out" << endl;
    }
    int get() const {return x;}
    void set(int x) {this->x = x;}
};

执行结果:

*I'm in
0x7fff62bb30c0 <-- from hello()
0x7fff62bb30c0 <-- from test1()
*I'm out
  • 这是 C++ 中的预期行为还是因为 g++ 优化而得到了这个结果?
  • A a(20)对象在 hello() 函数的堆栈中生成,并且应该在返回时被删除。对象栈如何不被删除并传递给调用者?
4

0 回答 0