我想知道C++标准对这样的代码的说法:
int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;
Run Code Online (Sandbox Code Playgroud)
在实践中,结果是ptr2NULL,但我想知道,这只是一个实现细节还是在标准中明确定义?
在不同的情况下,取消引用NULL指针应该导致崩溃,但是在这里我取消引用它以获得由编译器作为指针实现的引用,因此实际上没有实际的解除引用NULL.
我有这种内存布局:
0018FBD2 ?? ?? ?? ?? ?? ?? ?? ??
0018FBDA AA AA AA AA BB BB BB BB <- stuff I'm interested in
0018FBE2 ?? ?? ?? ?? ?? ?? ?? ??
Run Code Online (Sandbox Code Playgroud)
在C中,我会这样做:
int* my_array = (int*) 0x18FBDA;
my_array[0]; // access
Run Code Online (Sandbox Code Playgroud)
但是,我正在使用C++,我想声明一个引用:
int (&my_array)[2] = (???) 0x18FBDA;
Run Code Online (Sandbox Code Playgroud)
为了这样使用:
my_array[0]; // access
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的,我不知道如何施展它:
int (&my_array)[2] = (???) 0x18FBDA;
Run Code Online (Sandbox Code Playgroud)
我该怎么做?它甚至可能吗?
我最近学会了如何使用这个技巧将指针转换为引用.但是当我在访问器中执行此操作时,它似乎会创建一个未定义的行为,我无法理解为什么.
为什么我要这样做
我有一个class WalkerOwner拥有该实例的class Walker.Walker代码中的其他地方需要此实例,因此我为类提供了一个访问器(getter)WalkerOwner,它提供了一个引用.
class WalkerOwner
{
public:
...
Walker& getWalker() {return m_ownedWalker;} ;
private:
Walker m_ownedWalker;
};
Run Code Online (Sandbox Code Playgroud)
后来,我意识到WalkerOwner实际上应该由于某种原因在内部管理指向walker的指针.因为我不想重构我的其余代码,改变对指针的每个引用,我试图将指针转换为getter中的引用.
显示问题的代码
#include <iostream>
#include <string>
using std::string;
class Walker
{
public:
Walker() : m_travelledDistance(5) {};
~Walker(){};
void swank() { std::cout << "I have walked " << distanceAsString() << "! How good I am!" << std::endl; };
private:
// Calling this function makes the result even more impressive
string …Run Code Online (Sandbox Code Playgroud)