所以我有这个名为point的类,只是为了在每次构造和销毁对象时登录到控制台。我做了以下事情:
#include <iostream>
struct point{
point() {
std::cout << "ctor\n";
}
~point() {
std::cout << "dtor\n";
}
};
int main(){
int x = 3;
point* ptr = new point[x]{point()};
delete[] ptr;
}
Run Code Online (Sandbox Code Playgroud)
ctor
dtor
dtor
dtor
Run Code Online (Sandbox Code Playgroud)
This ended up calling the constructor just once, and the destructor 3 times, why? I know that this is bad, probably ub, but i would like to understand why. This other allocations give me the "expected" output:
ctor
dtor
dtor
dtor
Run Code Online (Sandbox Code Playgroud)
ctor
ctor
ctor …Run Code Online (Sandbox Code Playgroud) 这是一个非常快速的问题。我有以下代码:
struct integer {
int x;
int& ref() {
return x;
}
};
//main...
int* l = &integer{4}.ref();
std::cout << *l;
Run Code Online (Sandbox Code Playgroud)
我的问题是:&integer{4}.ref()因为它是一个临时对象,所以它不是一个右值吗?我怎么能有一个指向它的指针?这是未定义的行为吗?