简体   繁体   中英

class with unique_ptr problems

When using emplace_back a constructor must exist for the parameters passed (k,v) thus I need the constructor below. However since I use unique_ptr it complains about not being able to access 'delete' which I believe means I'm doing something that allows me to have more then one pointer.

I can't figure out the syntax. How do I write this constructor the right way?

struct KV{ 
    unique_ptr<string> k, v;
    KV(){} 
    KV (unique_ptr<string> k_,unique_ptr<string> v_):k(move(k_)),v(move(v_)){} 
};

Your constructor is OK. A possible problem is that you are not moving the two unique_ptr s when supplying them to your constructor:

#include <memory>
#include <string>

using namespace std;

struct KV{
   unique_ptr<string> k, v;
   KV(){}
   KV (unique_ptr<string> k_,unique_ptr<string> v_):k(move(k_)),v(move(v_)){}
};

int main()
{
   unique_ptr<string> p1(new string());
   unique_ptr<string> p2(new string());

   // KV v(p1, p2); // ERROR!
   KV kv(move(p1), move(p2)); // OK

   vector<KV> v;    
   v.emplace_back(move(p1), move(p2)); // OK       
}

UPDATE:

When VS2012 was shipped, VC11 did not support variadic templates. The correct implementation of emplace_back() should be variadic, but MS provided a dummy one. When the CTP has been shipped, only the compiler has been updated with support for variadic templates, but the STL hasn't been updated. Therefore, you still get the error.

There is not much to do about this if you can't change your compiler, apart from waiting for the next release of the product to be shipped. In the meanwhile, avoid using emplace_back() and use push_back() instead.

You haven't mentioned what container you're trying to emplace_back into, but assuming it is a vector , if your KV struct is really that simple, there's no need to declare any constructors. Just use aggregate initialization.

#include <memory>
#include <string>
#include <utility>
#include <vector>

using namespace std;

struct KV
{
   unique_ptr<string> k, v;
   // KV(){}
   // KV (unique_ptr<string> k_,unique_ptr<string> v_):k(move(k_)),v(move(v_)){}
};

int main()
{
   unique_ptr<string> p1(new string());
   unique_ptr<string> p2(new string());

   KV v{move(p1), move(p2)}; // initialize an instance
                             // this step is not necessary, you can skip it

   vector<KV> vec;

   vec.emplace_back(KV{move(v.k), move(v.v)});
}

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