这是奇怪的行为吗? [英] Is this strange behavior?
问题描述
以下是我的代码:
包含< iostream>
类测试{
public:
Test(){};
void print(){std :: cout<< "确定]; << std :: endl; };
};
int main(int argc,char ** argv){
Test * test = new Test ();
测试r = *测试;
删除测试;
r.print(); //这一行,这一行
}
我认为评论行会产生错误。
但输出OK通常,这种行为是对的吗?
嗨
Bo Yang写道:
< blockquote class =post_quotes>
int main(int argc,char ** argv){
Test * test = new Test();
Test r = *测试;
删除测试;
r.print(); //这一行,这一行
}
我认为评论行会产生错误。
但输出OK通常,这种行为是对的吗?
当然,你打印一份仍然存在的测试副本。
Markus
Bo Yang< st ****** @ mail.nankai.edu.cnwrites:
int main(int argc,char ** argv){
测试*测试=新测试();
测试r = *测试;
删除测试;
r.print(); //这一行,这一行
}
我认为评论行会产生错误。
No.
但输出正常,这种行为是对的吗?
是的。 r是一个局部变量(自动),它仍然在该行的范围内(实际上在这个块中)。它不是
对象测试指针的副本,而是测试值的副本到自己的内存中。
干杯,
Rudiger
" Bo Yang" < st ****** @ mail.nankai.edu.cn写信息
新闻:ek ********** @ news.cn99.com ...
以下是我的代码:
包括< iostream>
class测试{
public:
Test(){};
void print(){std :: cout<< "确定]; << std :: endl; };
};
int main(int argc,char ** argv){
Test * test = new Test ();
测试r = *测试;
删除测试;
r.print(); //这一行,这一行
}
我认为评论行会产生错误。
为什么这么认为?
但它输出正常,这是行为对吗?
是的,它是。
-Mike
Following is my code:
include <iostream>
class Test{
public:
Test(){};
void print(){ std::cout << "OK" << std::endl ; };
};
int main( int argc , char ** argv ){
Test * test = new Test();
Test r = *test ;
delete test ;
r.print(); //this line , this line
}
I think the comment line will produce an error.
But it output OK normally, is this behavior right?
Hi
Bo Yang wrote:
int main( int argc , char ** argv ){
Test * test = new Test();
Test r = *test ;
delete test ;
r.print(); //this line , this line
}
I think the comment line will produce an error.
But it output OK normally, is this behavior right?Absolutely, you call print on a copy of test that is still existent.
Markus
Bo Yang <st******@mail.nankai.edu.cnwrites:
int main( int argc , char ** argv ){
Test * test = new Test();
Test r = *test ;
delete test ;
r.print(); //this line , this line
}
I think the comment line will produce an error.No.
But it output OK normally, is this behavior right?Yes. r is a local variable (automatic), which is still in scope at
that line (actually in this block). It''s not a copy of the pointer of
object test, but a copy of the value of test into its own memory.
Cheers,
Rudiger
"Bo Yang" <st******@mail.nankai.edu.cnwrote in message
news:ek**********@news.cn99.com...Following is my code:
include <iostream>
class Test{
public:
Test(){};
void print(){ std::cout << "OK" << std::endl ; };
};
int main( int argc , char ** argv ){
Test * test = new Test();
Test r = *test ;
delete test ;
r.print(); //this line , this line
}
I think the comment line will produce an error.Why do you think so?
But it output OK normally, is this behavior right?Yes, it is.
-Mike
这篇关于这是奇怪的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!