指针和智能指针的区别
你能告诉我这段代码有什么问题吗?我在一次采访中被问到这个问题,我不确定
tClass 是一个测试类,它的方法 printSomething 可以打印 tClass 的成员。
tClass * A = new tClass();
f(A);
A->printSomething();
auto_ptr<tClass> * B = new tClass();
f(B);
B-> printSomething();
或者这是一个技巧问题。
Can you tell me what is wrong with this piece of code? I got asked this in an interview and I am not sure what's wrong with it
tClass is a test class with a method printSomething that prints members of tClass.
tClass * A = new tClass();
f(A);
A->printSomething();
auto_ptr<tClass> * B = new tClass();
f(B);
B-> printSomething();
or what this is a trick question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
auto_ptr 是一种智能指针,其运行前提是只有一方拥有该指针,如果该拥有方超出范围,则该指针将被删除。
当您将 auto_ptr 传递给函数时,您就“给出”了该指针的函数,因此您不再拥有它了。当您取消引用它时,您会得到空指针行为(当然,这是未定义的)。
但是,为了让您的代码能够编译,您必须稍微更改一下
B
的定义,这应该是因为 auto_ptr 不是类型(它是类型模板),并且您不这样做实际上想要一个指向该类型的指针,因为该类重载了这些行为。
auto_ptr is a type of smart pointer that operates under the premise that exactly one party owns the pointer, and if that owning party goes out of scope, the pointer gets deleted.
When you pass an auto_ptr to a function, you are "Giving" the function that pointer, and so you don't have it anymore. when you dereference it, you get a null pointer behavior (which is undefined, of course).
In order to get your code to compile, though, you have to change your definition of
B
a bit, it should besince auto_ptr is not a type (its a type template), and you don't actually want a pointer to that type at all, since the class overloads those behaviors.
问题是:
auto_ptr
类型。new tClass()
的类型为tClass*
,这不是分配给 B 的正确类型。Things wrong with it:
auto_ptr<tClass>
.new tClass()
is of typetClass*
which isn't the right type to assign to B.