Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new value and assign to a private unique_ptr in a class constructor?

How do I create new and assign a value to a private unique_ptr in the constructor of a class? Tyvm :^) Keith

My best effort:

#include <iostream>
#include <memory>

class A {
public:
    A() {};
    A(int);
    void print();
private:
    std::unique_ptr<int> int_ptr_;
};
A::A(int a) {
    int_ptr_ = new int(a);
}
void A::print() {
    std::cout << *int_ptr_ << std::endl;
}
int main() {
    A a(10);
    a.print();
    std::cout << std::endl;
}

Compiler result:

smartPointer2.1.cpp:13:11: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<int>’ and ‘int*’)
  int_ptr_ = new int(a);
like image 961
kmiklas Avatar asked Dec 24 '22 21:12

kmiklas


1 Answers

Write

A::A(int a) : int_ptr_( new int(a) )
{
}

Or you could write

A::A(int a) 
{
    int_ptr_.reset( new int(a) );
}

or

A::A(int a) 
{
    int_ptr_ = std::make_unique<int>( a );;
}

The first approach is better because in the other two apart from the default constructor there is called also an additional method or the move assignment operator.

like image 83
Vlad from Moscow Avatar answered Feb 15 '23 22:02

Vlad from Moscow