简体   繁体   中英

Can I use std::unique_ptr<BaseClass>(&DerivedClass)?

I got a segment fault but don't know why. Is it a problem to use std::unique_ptr<BaseClass>(&DerivedClassObj) ? Thanks.

Here's the code

# test.cc
#include <iostream>
#include <memory>
#include <vector>

using namespace std;

struct a {
  virtual void x(){cerr<<"a.x"<<endl;}
  virtual void y(){cerr<<"a.y"<<endl;}
  virtual void z(){cerr<<"a.z"<<endl;x();y();}
};

struct b: public a {
  virtual void y() {cerr<<"b.y"<<endl;}
};


int main(){
  cerr<<0<<endl;
  {
    b bb;
    vector<unique_ptr<a> > pb;
    cerr<<1<<endl;

    bb.z();
    pb.push_back(unique_ptr<a>(&bb));
    pb[0]->z();
    cerr<<2<<endl;
  }
  cerr<<3<<endl;
  return 0;
}

Here's the output

0
1
a.z
a.x
b.y
a.z
a.x
b.y
2
Segmentation fault (core dumped)

Here's the compile command

$ g++ -std=c++0x    test.cc   -o test

and g++ version info.

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 

Trying to wrap a smart pointer around a pointer to an object with automatic storage duration ("on the stack", for newbs) is undefined; you shan't do it.

Besides that, std::unique_ptr takes ownership of its underlying pointer, deleting the pointee when it's done; this is a problem because you gave it a pointer to an object "on the stack", which already gets automatically deleted. So, you'd be deleting your object twice.

I suggest that you dynamically allocate your object, with the following:

unique_ptr<a> ptr(new b);
ptr->z();
pb.push_back(std::move(ptr));

…then don't use ptr again.

You're also going to need a virtual destructor in a .

You should find yourself a good book on C++ because these are fairly basic concepts that should be covered in your reading material.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM