简体   繁体   English

用于赋值的参数化构造函数

[英]Parameterized constructor for assignment

I've noticed some behaviour which I can't understand in parameterized constructors. 我注意到一些我在参数化构造函数中无法理解的行为。 Given the following program: 鉴于以下计划:

#include <iostream>
using namespace std;

class A {
public:
    int x;

    A() {}

    A(int i) : x(i){
        cout << "A\n";
    }
    ~A(){
        cout << "dA\n";
    }

};

int main(){
    A p;
    p = 3;
    cout << p.x << endl;
    p = 5;
    cout << p.x << endl;
    return 0;
}

I get as output: 我得到输出:

A
dA
3
A
dA
5
dA

This means that using = triggers the parameterized constructor, destroys the object on which it's called and creates a new object. 这意味着using =触发参数化构造函数,销毁它所调用的对象并创建一个新对象。 I cannot understand this behaviour and I can't find the answer in the standard ( I am sure it is there somewhere, but it may be stated in a sophisticated way). 我无法理解这种行为,我无法在标准中找到答案(我确信它存在于某个地方,但可能以复杂的方式陈述)。 Could someone help me with an explanation? 有人可以帮我解释一下吗?

With a statement like 有一个声明

p = 3;

what you're actually doing is 你真正在做的是

p = A(3);

which really translates to 这实际上转化为

p.operator=(A(3));

The temporary A object created by A(3) of course needs to be destructed, it is temporary after all. A(3)创建的临时A对象当然需要被破坏,毕竟它是暂时的

The object p itself will not be destructed by the assignment. 对象p本身不会被赋值破坏。

The phrase you're probably looking for is "implicit conversion". 您可能正在寻找的短语是“隐式转换”。

If you add a copy constructor and an assignment operator, and then give each object a unique ID, it's easier to see where things go: 如果添加复制构造函数和赋值运算符,然后为每个对象提供唯一的ID,则更容易看到事情的进展:

int counter = 0;

class A {
public:
    int id;

    A(): id(++counter) {cout << "A(): " << id << "\n";}

    A(int i) : id(++counter) {cout << "A(" << i << "): " << id << "\n";}

    // Don't copy the id.
    // (This isn't used anywhere, but you can't see that it's not used unless it exists.)
    A(const A& a) : id(++counter) {cout << "A(" << a.id << "): " << id << "\n";}

    // Don't copy the id here either.
    A& operator=(const A&a) {cout << id << " = " << a.id << "\n"; return *this;}

    ~A(){cout << "destroy: " << id << "\n";}
};

int main(){
    A p;
    cout << "p is " << p.id << "\n";
    p = 3;
    cout << "p is " << p.id << "\n";    
    p = 5;
    cout << p.id << "\n";
}

Output: 输出:

A(): 1
p is 1
A(3): 2
1 = 2
destroy: 2
p is 1
A(5): 3
1 = 3
destroy: 3
1
destroy: 1

As you can see, the parameterized constructor is used to create a temporary object whose value can be assigned to p , and that temporary is destroyed immediately after that. 如您所见,参数化构造函数用于创建一个临时对象,其值可以分配给p ,之后会立即销毁该临时对象。
You can also see that p is alive and well until the very end. 你也可以看到p是活着的,直到最后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM