我有以下代码片段:
class ABC{
public:
int a;
void print(){cout<<"hello"<<endl;}
};
int main(){
ABC *ptr = NULL:
ptr->print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它运行成功.有人可以解释一下吗?
#include "iostream"
using namespace std;
class A
{
public:
void mprint()
{
cout<<"\n TESTING NULL POINTER";
}
};
int main()
{
A *a = NULL;
a->mprint();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我输出为"TESTING NULL POINTER".任何人都可以解释为什么这个程序打印输出而不是崩溃.我在Dev C++和aCC编译器上检查了它们都给出了相同的结果.
这里出现了一个问题,当一个指针变得晃来晃去时,问"为什么这个工作".答案是它是UB,这意味着它可能起作用.
我在一个教程中学到了:
#include <iostream>
struct Foo
{
int member;
void function() { std::cout << "hello";}
};
int main()
{
Foo* fooObj = nullptr;
fooObj->member = 5; // This will cause a read access violation but...
fooObj->function(); // Because this doesn't refer to any memory specific to
// the Foo object, and doesn't touch any of its members
// It will work.
}
Run Code Online (Sandbox Code Playgroud)
这相当于:
static void function(Foo* fooObj) // Foo* essentially being the "this" pointer
{
std::cout << "Hello";
// Foo …Run Code Online (Sandbox Code Playgroud) 我最近开始学习 C++ 中的智能指针和移动语义。但我不明白为什么这段代码有效。我有这样的代码:
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test()
{
cout << "Object created" << endl;
}
void testMethod()
{
cout << "Object existing" << endl;
}
~Test()
{
cout << "Object destroyed" << endl;
}
};
int main(int argc, char *argv[])
{
Test* testPtr = new Test{};
{
unique_ptr<Test> testSmartPtr(testPtr);
}
testPtr->testMethod();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的输出是:
Object created
Object destroyed
Object existing
Run Code Online (Sandbox Code Playgroud)
为什么行testPtr->testMethod()有效?如果指针是左值,unique_ptr 不会在销毁时删除分配给它的指针吗?
编辑:我从评论中了解到,此方法不会检查指针是否存在。如果是这样,有没有办法检查指针是否有效?
编辑:我了解到我不应该对无效指针做任何事情。感谢您的所有回答和评论。
编辑:即使这个代码也有效:
#include <iostream>
#include <memory> …Run Code Online (Sandbox Code Playgroud)