使用其他scoped_ptr初始化boost :: scoped_ptr会导致问题。此代码正确

我不熟悉Boost库,尝试使用boost::scoped_ptr,它指出该智能指针无法复制或移动。但是我在玩一些代码,发现了一个问题。我能够创建scoped_ptr的新实例,并使用现有有效的scoped_ptr对其进行初始化。因此,如果scoped_ptr的作用域之一已结束并释放了内存,则其他scoped_ptr仍会认为其有效指针并尝试访问。它在运行时给我错误。

我正在使用cygwin g ++编译器开发boost库版本1.66,并在编译时使用std = c ++ 03选项。

#include<boost/scoped_ptr.hpp>
#include<iostream>

using namespace std;

int main(){
    boost::scoped_ptr<int> pi(new int(9));
    cout << *pi << endl;
    cout << uintptr_t(pi.get()) << endl;

    boost::scoped_ptr<int> ppi(pi.get()); // initialized with same memory pointed by pi.
    cout << *ppi << endl;                 // so ownership of same memory is with pi.
    cout << uintptr_t(ppi.get()) << endl; // as well as with ppi.

    pi.reset(new int(12)); //its previous memory location pointing to 9 is deallocated.

    cout << *ppi << endl;                  // throws garbage value.. 
    cout << uintptr_t(ppi.get()) << endl;  // shows same memory location it had previous memory shown by pi. 

    cout << *pi << endl;
    cout << uintptr_t(pi.get()) << endl;

    return 0;
}

因此,下面是编译良好后运行的代码的快照...

-> g++ -std=c++03 -Wall scoped_ptr.cpp 

-> ./a.exe 
9
25769804960
9
25769804960
-2144292696
25769804960
12
25769879920
Aborted (core dumped)

执行结束时显示核心转储,在以上运行中错误地显示了-2144292696

我还检查了boost::scoped_ptr能否将其分配给指针
int * p = pi.get()语句可以很好地编译(这可以吗?)

上述操作用其他scoped_pt初始化scoped_ptr r是否有效?

pk110987 回答:使用其他scoped_ptr初始化boost :: scoped_ptr会导致问题。此代码正确

  

上述操作与其他scoped_ptr一起初始化scoped_ptr是否有效?

不。 Boost documentation读为:

  

explicit scoped_ptr(T * p = 0); // never throws

     

构造一个scoped_ptr,存储p的副本,该副本必须已通过C ++ new表达式分配或为0

当使用由另一个智能指针保存的原始指针初始化一个智能指针时,您不会转让所有权,您只需复制原始指针即可。因此,该指针将被delete多次,这是未定义的行为。

您的代码本质上是这样的:

int* p = new int;
delete p;  // when you call pi.reset()
delete p;  // when ppi goes out of scope

.get()返回存储的原始指针。它不会检查其有效性。

要转让所有权,您应该移动-分配智能指针本身。使用std::unique_ptr和C ++ 11的简单示例:

auto p = std::unique_ptr<int>(new int);
// auto p1 = std::unique_ptr<int>(p.get()); // same error
auto p2 = std::move(p); // fine,transfers ownership from p to p2; 
                        // p will not delete the raw pointer it previously held

boost::scoped_ptr不支持所有权转移。

本文链接:https://www.f2er.com/3158362.html

大家都在问