다음 코드에서 'main()'의 마지막 줄에서 생성 된 개체는 식 끝 전에 소멸됩니다. 소멸자는 '< <'이 실행되기 전에 호출됩니다. 이게 그것이 있어야하는 방법인가요?익명 (이름이없는) 변수의 개체 수명이 C++입니다.
Hello
from A: 0x80495f7
from A: Hello
이것은 GDB 로그입니다 :
#include <string>
#include <sstream>
#include <iostream>
using std::string;
using std::ostringstream;
using std::cout;
class A : public ostringstream
{
public:
A() {}
virtual ~A()
{
string s;
s = str();
cout << "from A: " << s << std::endl;
}
};
int
main()
{
string s = "Hello";
A os;
os << s;
cout << os.str() << std::endl;
A() << "checking this";
}
이
는 출력(gdb) b os.cxx : 18
Breakpoint 1 at 0x80492b1: file os.cxx, line 18. (2 locations)
(gdb) r
Starting program: /home/joe/sandbox/test/os
Hello
Breakpoint 1, ~A (this=0xbffff37c, __in_chrg=<value optimized out>, __vtt_parm=<value optimized out>) at os.cxx:18
18 cout << "from A: " << s << std::endl;
(gdb) p s.c_str()
$1 = 0x804b45c "0x80495f7"
(gdb) p *s.c_str()
$2 = 48 '0'
(gdb) c
Continuing.
from A: 0x80495f7
Breakpoint 1, ~A (this=0xbffff2bc, __in_chrg=<value optimized out>, __vtt_parm=<value optimized out>) at os.cxx:18
18 cout << "from A: " << s << std::endl;
(gdb) p s.c_str()
$3 = 0x804b244 "Hello"
(gdb) p *s.c_str()
$4 = 72 'H'
(gdb) c
Continuing.
from A: Hello
Program exited normally.
(gdb)
좋은 설명, 당신은 기록했다. – iain