小编Den*_*cor的帖子

新的数组分配

所以我有这个名为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)

c++ arrays new-operator

6
推荐指数
1
解决办法
154
查看次数

指向右值对象成员变量的指针

这是一个非常快速的问题。我有以下代码:

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()因为它是一个临时对象,所以它不是一个右值吗?我怎么能有一个指向它的指针?这是未定义的行为吗?

c++ pointers rvalue

4
推荐指数
1
解决办法
60
查看次数

标签 统计

c++ ×2

arrays ×1

new-operator ×1

pointers ×1

rvalue ×1