如果你试图cout指向volatile类型的指针,即使是你通常希望cout打印字符串的volatile指针,你只需要得到'1'(假设指针不是null我认为).我假设输出流operator <<是专门用于volatile指针的模板,但我的问题是,为什么?什么用例激发了这种行为?
示例代码:
#include <iostream>
#include <cstring>
int main()
{
char x[500];
std::strcpy(x, "Hello world");
int y;
int *z = &y;
std::cout << x << std::endl;
std::cout << (char volatile*)x << std::endl;
std::cout << z << std::endl;
std::cout << (int volatile*)z << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hello world
1
0x8046b6c
1
Run Code Online (Sandbox Code Playgroud) 我想将一个对象分配给同一类型的volatile对象,但是由于编译器错误而无法执行此操作.如何改变程序来实现呢?除了让它工作,为什么我不能直接做到这一点?
我在这里使用Visual Studio 2010作为编译器.
class A
{
public:
};
int _tmain()
{
A a;
volatile A va;
va = a; // compiler error:C2678 here
return 0;
}
Run Code Online (Sandbox Code Playgroud) 大多数时候,我这样做.
class a {
public:
~ a() {
i = 100; // OK
delete (int *)j; // Compiler happy. But, is it safe?
// The following code will lead compilation error : delete j;
}
private:
volatile int i;
volatile int *j;
};
int main() {
a aa;
}
Run Code Online (Sandbox Code Playgroud)
但是,我在这里看到一篇文章:
抛弃volatile允许通过非易失性引用访问对象.这可能导致未定义的,也许是非预期的程序行为.
那么,上面代码示例的解决方法是什么?
以下是我使用时收到的错误消息
删除j
注意,这是从VC6输出的(不要问我为什么使用VC6!)
c:\ projects\a\a.cpp(5):错误C2664:'delete':无法将参数1从'volatile int*'转换为'void*'转换失去限定符
我试图弄清楚为什么在关闭以下代码的编译器优化后停止工作:
bool send_atcmd(char* atcmd, char* expected_response, unsigned int timeout)
{
volatile char* buf = uart_get_rx_buf(UART_MODEM);
bool response_match = false;
if (modem_powered_on)
{
__delay_cycles((unsigned long)500 * DELAY_MS);
uart_clear_rx_buf(UART_MODEM);
uart_puts(UART_MODEM, atcmd);
uart_putc(UART_MODEM, '\r');
timer_ms = 0;
while (!response_match && timer_ms <= timeout)
{
//__nop();
if (strstr(buf, expected_response) != NULL)
response_match = true;
}
uart_clear_rx_buf(UART_MODEM);
}
return response_match;
}
Run Code Online (Sandbox Code Playgroud)
代码使用msp430-gcc编译,buf指向接收调制解调器操作的uart端口的缓冲区.一切正常,直到没有优化(-O0),但是当 条件为假时,当while循环上的优化完成时timer_ms <= timeout,strstr(buf, expected_response)永远会返回!NULL.这是因为buf的内容似乎没有更新.
但是,if (strstr(buf, expected_response) != NULL)在while循环之前放置任何东西
,例如取消注释nop()会使代码正常工作.
将buf在ISR更新. …