c++ - 我实际上是在此处将对象存储在 cpu 寄存器中吗?

标签 c++

<分区>

在这个程序中,我使用了 volatile 寄存器对象, 我实际上是将我的对象存储到此处的寄存器吗?
为什么我得到的对象地址是 1? 请分享您对此的看法。

#include <iostream>
using namespace std;


class a{
    int i,j,k[999];
    long double  arr[9999999];
    public:
        a(){
            i=77; j=89;
            cout<<"\nctor\n";
        }
        void disp()volatile {
            cout<<"\ni = "<<i<<" j = "<<j<<"\n";
        //  delete this;
        }
        ~a(){
            cout<<"\ndtor\n";
        }
};


int main(){
    register volatile a *ao = new a;
    cout<<"address of a = "<<ao; //out puts "1" for me; (My processor is core i3 330M).
    ao->disp();
     delete ao;
}

最佳答案

这是显而易见的,因为没有调用 delete 这意味着您会发生内存泄漏。您需要显式调用 delete 来避免这种情况,或者更好:使用智能指针。

此外,寄存器在C++中会被忽略。是basically deprecated.您可以从 C++ 标准中阅读它:

A register specifier has the same semantics as an auto specifier together with a hint to the implementation that the object so declared will be heavily used. [Note: the hint can be ignored and in most implementations it will be ignored if the address of the object is taken. —end note]

因此,这里的寄存器用法是转移注意力。

打印出1是因为以下原因:

"When you pass in a volatile pointer, the second overload can't apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, so the first overload is chosen, and the result you see is 1 or 0."

... 来自 here .

因此,如果您删除 volatile,它将不再打印 1

关于c++ - 我实际上是在此处将对象存储在 cpu 寄存器中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896855/

相关文章:

c++ - 我应该像这样使用 constexpr 吗?

C++ 管道错误,pipe_wait 永远

c++ - 如何使用 GTK 信号?

c++ - 强制接口(interface)的模板

c++ - 为什么我可以访问我刚刚从 C++ 中的 STL vector 中删除的元素?

c# - 需要帮助理解 _set_security_error_handler()

c++ - 如何将一组统一缓冲区对象加载到着色器中?

c++ - 使用abi compliance checker时出错的原因是什么?

c++ - 错误 : ‘Integer Integer::operator<<(const Integer&, const Integer&)’ must take exactly one argument

c++ - 从 txt 文件读取行后字符串比较失败