gpt4 book ai didi

c++ - 在 C++ 中初始化为自身的对象

转载 作者:太空狗 更新时间:2023-10-29 20:11:42 24 4
gpt4 key购买 nike

例如,我有代码:

class test{
public:

test(){
cout<<endl<<"TEST";
}

void another(){
cout<<endl<<"Another";
}

};

int main(){
test chk = chk;
chk.another();
}

在这里,我对新创建的类型为 test 的对象进行了初始化。

这样的初始化是否有特殊用途,除了初始化 test chk; 而不是 test chk = chk; 之外,这样的初始化是否做任何事情?

我知道如果对象被初始化为自身,则构造函数不能被调用,但为什么?

我想了解更多有关对象自身初始化的信息。

最佳答案

你可以这样写:

test chk = chk;

[basic.scope.declarative]/p1

The potential scope of the first j begins immediately after that j

implicit copy constructor因此被调用。您可能已经使用自己的执行了一些额外的初始化:

test(const test&) {
cout << endl << "copy ctor";
}

请记住,这不是一个好的做法,它甚至可能导致 undefined behavior在某些情况下,Clang 总是发出 -Wuninitialized 警告。

关于c++ - 在 C++ 中初始化为自身的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31759210/

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