gpt4 book ai didi

c++ - 引用具有删除类型 (void*) 的指针

转载 作者:行者123 更新时间:2023-12-02 10:12:55 27 4
gpt4 key购买 nike

我可以接受 T*&来自 T* .现在我需要存储我的T*以类型删除的方式,更具体地说是 void* .我可以接一个T*&来自 void* ? (当然知道我的 void* 确实指向 T s)
例子:

#include <iostream>
#include <cstdlib>
#include <numeric>

int main() {
int n = 10;
void* mdbuf = malloc(n*sizeof(double));
double* mdarr = (double*)mdbuf;
std::iota(mdarr,mdarr+n,0.); // initialize the memory with doubles

// solution 1: works but not what I want since I want to refer to the type-erased mdbuf variable
double*& mdarr_ref = mdarr; // ok, now mdarr_ref refers to variable mdarr

// solution 2: does not compile
double*& mdbuf_ref = (double*)mdbuf; // error: cannot bind non-const lvalue reference of type 'double*&' to an rvalue of type 'double*'

// solution 3: compiles and work but I want to be sure this is not out of pure luck: is it undefined behavior?
double*& mdbuf_ref = (double*&)mdbuf; // we would like mdbuf_ref to refer to variable mdbuf. It compiles...
std::iota(mdbuf_ref,mdbuf_ref+n,100.);
for (int i=0; i<n; ++i) {
std::cout << mdbuf_ref[i] << ", "; // ...does what we want in this case... is it valid however?
}
}
编辑:也许一种看待它的方法如下:
double d;
void* v_ptr = &d;
double* d_ptr = (double*)v_ptr; // (1) valid
double& d_ref = d; // (2) valid
double& d_ref2 = (double&)d; // (3) valid? Should be the same as (2) ?
double*& d_ref3 = (double*&)v_ptr; // (4)
问题是:(4)有效吗?如果(1)和(3)成立,它只是链接两者,所以我希望它是有效的,但我想要一些证据

最佳答案

我将采用您的第二个示例并使用别名重写其中的部分内容,以更好地说明您的要求。

using V = void*;
using K = double*;

double d;
V v_ptr = reinterpret_cast<V>(&d);
V &v_ptr_ref1 = v_ptr; //Refers to the `V` object denoted by `v_ptr`.
K d_ptr = &d;
K &d_ptr_ref1 = d_ptr; //Refers to the `K` object denoted by `d_ptr`.
V &d_ptr_ref2 = reinterpret_cast<V&>(d_ptr);
所以,我们有两种类型: KV .在最后一行,我们初始化了一个对 V 的引用。使用 K 类型的对象.所以 d_ptr_ref2初始化为引用 K 类型的对象, 但引用的类型是 V .
它们是否“只是”指针类型并不重要。在 C++ 中,指针是对象类型,它们遵循任何其他对象类型的所有规则。
C++ 的严格别名规则禁止在某些非常特定的情况之外通过不同类型的左值(如引用)访问一种类型的对象。具体异常(exception)情况因版本而异,但没有 C++ 版本中的 void*double*是一个异常(exception)。
尝试访问 d_ptr_ref2表示您正在访问类型为 K 的对象通过不相关类型的引用 V .这违反了严格的别名,从而产生了未定义的行为。

关于c++ - 引用具有删除类型 (void*) 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861510/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com