C++ c++;,匿名(未命名)变量的对象生存期
在下面的代码中,在“main()”的最后一行中构造的对象似乎在表达式结束之前被销毁。在“之前调用析构函数我相信您看到的行为是因为“匿名临时变量不能作为非常量引用传递到函数中”的规则(当然不是真的,但在不同的编译器上有未定义的行为或不同的行为)。因此,它确实转到A,直到执行完full语句后才被删除 您遇到的问题不是由删除和打印非斜体数据引起的,而是由r值引用引起的。注释性实例只能通过值或常量引用传递C++ c++;,匿名(未命名)变量的对象生存期,c++,C++,在下面的代码中,在“main()”的最后一行中构造的对象似乎在表达式结束之前被销毁。在“之前调用析构函数我相信您看到的行为是因为“匿名临时变量不能作为非常量引用传递到函数中”的规则(当然不是真的,但在不同的编译器上有未定义的行为或不同的行为)。因此,它确实转到A,直到执行完full语句后才被删除 您遇到的问题不是由删除和打印非斜体数据引起的,而是由r值引用引起的。注释性实例只能通过值或常量引用传递 这意味着你们的类将支持操作符很好的解释,你们在我回答的时候发布了。 #include <st
这意味着你们的类将支持
操作符很好的解释,你们在我回答的时候发布了。
#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";
}
Hello
from A: 0x80495f7
from A: Hello
(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)
struct A {
f()
};
void g(A & a) {
}
void foo() {
A a;
a.f();
g(a);
A().f();
g(A()); // This does not compile
}
class A
{
ostringstream mystream;
public:
A () {}
virtual ~A ()
{
cout << "from A: " << mystream.str(); << std::endl;
}
ostream & stream()
{
return mystream;
}
};
int
main ()
{
string s = "Hello";
A os;
os.stream() << s;
A().stream() << "checking this";
}
#define TRACE_ERROR if (A::testLevel(A::Error) A(A::Error).stream()
#define TRACE_INFO if (A::testLevel(A::Info) A(A::Info).stream()
void foo()
{
int a = ..
std::string s = ..
TRACE_INFO << "Some information " << a << " message: " s;
}