Why would I use get()
with *
, instead of just calling *
?
Consider the following code:
auto_ptr<int> p (new int);
*p = 100;
cout << "p points to " << *p << '\n'; //100
auto_ptr<int> p (new int);
*p.get() = 100;
cout << "p points to " << *p.get() << '\n'; //100
Result is exactly the same. Is get()
more secure?
答案 0 :(得分:6)
Practically no difference.
In case of *p
, the overloaded operator*
(defined by auto_ptr
) is invoked which returns the reference to the underlying object (after dereferencing it — which is done by the member function). In the latter case, however, p.get()
returns the underlying pointer which you dereference yourself.
I hope that answers your question. Now I'd advise you to avoid using std::auto_ptr
, as it is badly designed — it has even been deprecated, in preference to other smart pointers such as std::unique_ptr
and std::shared_ptr
(along with std::weak_ptr
).
答案 1 :(得分:5)
*p
calls auto_ptr::operator*
, which dereferences the managed pointer.
*p.get
first calls method auto_ptr::get
, which returns the managed pointer, which is then dereferenced by operator *
.
These will provide exactly the same result once executed: the managed pointer is dereferenced, and there will be no additional checking when using get
.
Note that auto_ptr
is deprecated since C++11. It is dangerous because ownership of the pointer is transfered when copying:
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
} // copy_of_p is destroyed, and deletes its owned pointer
// p is now a dangling pointer
To avoid the problem, you had to "manage the managed pointers":
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
// ...
p = copy_of_p; // p gets back ownership
} // copy_of_p is destroyed, but doesn't delete pointer owned by p
// p is still valid
Use unique_ptr
or shared_ptr
instead.
答案 2 :(得分:4)
There is no effective difference. operator*
is defined to return *get()
(cppreference).
You should consider using unique_ptr
in auto_ptr
's stead. The latter has been removed from the current C++ standard and has very non-intuitive yank-on-copy behaviour.
答案 3 :(得分:0)
不要在智能指针上使用get()
(无论auto_,unique_,shared_还是其他)。这将返回一个不受RAII类控制的裸指针。这开辟了将指针指向另一个RAII类的各种可能性(稍后导致双重删除),或者调用者做了一些愚蠢的事情,比如删除指针(再次导致双删除)。只需取消引用智能指针。
PS:仅限专家:是的,从智能指针中提取原始指针还有其他正当理由。但是一般情况下不使用get(),使用它的次数会变成红色标志,这里有一些时髦的东西,请注意!&#34;。