[问题] VC的constructor 呼叫了 destructor?

楼主: donkeychen (Bad_To_The_Bone)   2014-09-22 15:53:02
开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)

问题(Question):
在Programming版问了如何trace code的开始与结束的时候
版上大大提供
宣告一个物件 建构子的时候印出开始符号 解构子的时候印出结束符号
进function就宣告此物件
在BCB测试顺利
在VC下 建构子一呼叫完解构子就被呼叫
预期的正确结果(Expected Output):
line1 (表示开始)
line2 (表示function内容)
line3 (表示结束)
错误结果(Wrong Output):
line1
line3
line2
line3
程式码(Code):(请善用置底文网页, 记得排版)
.h
#include <iostream>
using namespace std;
struct BEGINEND
{
public:
BEGINEND(char* file, int line, wstring str);
~BEGINEND(void);
private:
char *file_;
int line_;
wstring str_;
};
=========================================================
.cpp
#include "stdafx.h"
#include "test.h"
#include <iostream>
using namespace std;
BEGINEND::BEGINEND(char* file, int line, wstring str)
{
void* ptr;
ptr = this;
file_ = file;
line_ = line;
str_ = str;
{
cout << "line1" << endl;
}
}
BEGINEND::~BEGINEND(void)
{
void* ptr;
ptr = this;
cout << "line3" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
BEGINEND be = BEGINEND(__FILE__, __LINE__, L"haha");
cout << "line2" << endl;
return 0;
}
补充说明(Supplement):
错误输出的情况我有试着把this印出
结果
line1
line3
lien2
line3
红色两行的this与绿色行的this不同个
想请教一下这情况是哪边出问题了呢
谢谢
作者: CindyLinz (Cindy Wang)   2014-09-22 16:02:00
觉得红色部分是 BEGINEND(__FILE__...) 的生和灭然后 be = 是从 copy constructor 建立 be, 所以呼叫到没有 line1 的 constructor, 就没印 line1 了最后面绿色是 be 的毁灭
作者: azureblaze (AzureBlaze)   2014-09-22 16:18:00
要弄这种东西建议用 X a(args...); 这种方式
作者: CindyLinz (Cindy Wang)   2014-09-22 17:02:00
不过 VC++ 这行为有一点怪, 你要不要附一下版本? ^^|
楼主: donkeychen (Bad_To_The_Bone)   2014-09-22 17:09:00
喔喔 感谢AZ大 跟CI大....2005的^^;改AZ大的宣告可以正常了 不会有红色的LINE3
作者: CindyLinz (Cindy Wang)   2014-09-22 17:14:00
我用 g++ 试类似的写法, 是会自动变成 azureblaze 讲的效果.. 而且 optimize 都关了, 用 -O0 也是.. @@"g++ 4.8.2
作者: azureblaze (AzureBlaze)   2014-09-22 17:32:00
gcc似乎要-fno-elide-constructors才关得掉
楼主: donkeychen (Bad_To_The_Bone)   2014-09-22 18:43:00
原来是compiler的行为~
作者: suhorng ( )   2014-09-22 19:33:00
噢~所以问题解决了? 还没回你信XD感觉应该如二楼所说, 是呼叫 copy constructor所以还有临时物件的建构解构吧 (不太熟, 不敢乱说XD)
楼主: donkeychen (Bad_To_The_Bone)   2014-09-23 11:29:00
感谢大大^^

Links booklink

Contact Us: admin [ a t ] ucptt.com