gpt4 book ai didi

c++ - 这段代码有什么问题?我必须使用指向 union 的 volatile 指针,这会导致运算符重载错误 =

转载 作者:行者123 更新时间:2023-11-28 00:55:31 24 4
gpt4 key购买 nike

constvolatile.cpp:91:9:错误:将“volatile GENERIC_COMMAND”作为“const GENERIC_COMMAND& GENERIC_COMMAND::operator=(const T&) [with T = COMPLETION_WAIT, GENERIC_COMMAND = GENERIC_COMMAND]”的“this”参数传递 [-fpermissive]

            #include <iostream>
using namespace std;

typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;

union GENERIC_COMMAND
{
struct
{
uint64_t first_operand : 60;
uint64_t opcode : 4;
uint64_t second_operand : 64;
};

struct
{
uint32_t dword1;
uint32_t dword2;
uint32_t dword3;
uint32_t dword4;
};

struct
{
uint64_t qword1;
uint64_t qword2;
};

GENERIC_COMMAND() {
}
GENERIC_COMMAND(volatile const GENERIC_COMMAND&){}

template <typename T>
volatile GENERIC_COMMAND& operator=(const T& rhs) volatile
{
this->dword1 = rhs.dword1;
this->dword2 = rhs.dword2;
this->dword3 = rhs.dword3;
this->dword4 = rhs.dword4;
return *this;
}
};


union COMPLETION_WAIT
{
struct
{
uint64_t s : 1;
uint64_t i : 1;
uint64_t f : 1;
uint64_t store_address : 49;
uint64_t reserved1 : 8;
uint64_t opcode : 4;
uint64_t store_data : 64;
};
struct
{
uint32_t dword1;
uint32_t dword2;
uint32_t dword3;
uint32_t dword4;
};
};


void add_completion_wait_command(uint32_t s, uint32_t i, uint32_t f,
uint64_t store_address, uint64_t store_data,
bool auto_flush)
{
COMPLETION_WAIT command;
command.dword1 = 0;
command.dword2 = 0;
command.dword3 = 0;
command.dword4 = 0;

command.s = s;
command.i = i;
command.f = f;
command.store_address = store_address >> 3;
command.opcode = 0x1;
command.store_data = store_data;

GENERIC_COMMAND generic;
static_cast<GENERIC_COMMAND>(generic = command);

}

main()
{
cout<< "in main"<< endl;
volatile GENERIC_COMMAND* A;//this has to be volatile only.
COMPLETION_WAIT cw;
A = new volatile union GENERIC_COMMAND;
static_cast<GENERIC_COMMAND>(A[0] = cw);

}

最佳答案

您的 operator= 需要可变。就像成员函数需要是 const 才能在 const 对象上调用一样。如果您的成员函数不是 volatile,编译器将优化它的函数体,这不是您想要的 volatile 对象。所以语言有这个有用的规则。

众所周知,即使使用隐式声明的 operator=,也会发生此错误,并且被记录为与 C 语言不兼容的问题之一。

编辑:我想提一下,您分配给的对象不是 volatile 的,因此编译器可以自由地优化对它的操作,即使用于访问它的指针具有 volatile 限定符。给它的类型加上volatile

new volatile union GENERIC_COMMAND

关于c++ - 这段代码有什么问题?我必须使用指向 union 的 volatile 指针,这会导致运算符重载错误 =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11630455/

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