gpt4 book ai didi

C++ 将引用成员绑定(bind)到构造函数参数

转载 作者:行者123 更新时间:2023-11-30 05:09:59 27 4
gpt4 key购买 nike

在 gcc 8 上运行以下代码时(https://wandbox.org/,带有“g++ prog.cc -Wall -Wextra -std=c++1z”):

#include <iostream>

class B{
public:
B(): copy(false){ std::cout << "B-constructed" << std::endl;}
B(const B& b): copy(true){ std::cout << "B-copy-constructed" << std::endl; }
~B(){ std::cout << (copy?"B-destructed":"B-(copy)-destructed") << std::endl;}

bool copy;
};

class A{
public:
A(B b): bref(b){std::cout << "A-constructed" << std::endl;}
~A() {std::cout << "A-destructed" << std::endl;}
B &bref;
};


void f(){
B b;
A a(b);

std::cout << "f over" << std::endl;
}

int main()
{
f();

std::cout << "main over" << std::endl;
return 0;
}

产生以下输出:

B-constructed
B-copy-constructed
A-constructed
B-destructed
f over
A-destructed
B-(copy)-destructed
main over

对象销毁的顺序似乎很不寻常。这就好像延长了构造函数参数的生命周期。该标准是否说明了将成员引用绑定(bind)到构造函数参数?

我认为标准中的这句话不适用,因为参数不是临时对象(但我不知道“临时表达式”的定义):

A temporary expression bound to a reference member in a mem-initializer is ill-formed. [ Example:

struct A {

A() : v(42) { } // error

const int& v;

};

—end example ]

最佳答案

你的析构函数有一个逻辑错误,因为当 copy 错误时你打印了一个拷贝被破坏。

改变这个:

~B(){ std::cout << (copy?"B-destructed":"B-(copy)-destructed") << std::endl;}

为此:

~B(){ std::cout << (copy?"B-(copy)-destructed":"B-destructed") << std::endl;}

现在输出:

B-constructed
B-copy-constructed
A-constructed
B-(copy)-destructed
f over
A-destructed
B-destructed
main over

简洁明了(Order of member constructor and destructor calls)。


标准是否说明了将成员引用绑定(bind)到构造函数参数?

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.deallocation]), and using the properties of the glvalue that do not depend on its value is well-defined.

Source

关于C++ 将引用成员绑定(bind)到构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45880561/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com