Thread: Unique pointer and a vector in the class constructor

  1. #1
    Registered User
    Join Date
    May 2008

    Unique pointer and a vector in the class constructor


    I was mildly surprised when I realized that I cannot initialize the vector directly like in the commented out command, but have to use a default constructor. Surprised because initialization directly via the constructor (i.e. without a unique pointer) works fine. I am doing this right, or is there a better way? Because doing it this way on a class with many vectors bloats the code.

    #include <iostream>
    #include <memory>
    #include <vector>
    struct Gauge
        std::vector<int> Dial;
        Gauge() = default;
        Gauge(std::vector<int> dial) : Dial(dial) {}
    int main ()
        // auto gauge = std::make_unique<Gauge> ({1,2});
        auto gauge = std::make_unique<Gauge> ();
        gauge->Dial = {1,2};
        std::cout << gauge->Dial[0] << '\n';

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    I think you may need a std::initializer_list constructor to do that. If you don't go that route, what about:
    auto gauge = std::make_unique<Gauge>(std::vector{1, 2});
    But an initializer_list constructor might be better so as to not expose the internals of the class... but you already have the member variable as public so it might not matter.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2008
    Yes, this works! Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 12-15-2012, 08:16 PM
  2. initializing a vector of structs in class constructor
    By edishuman in forum C++ Programming
    Replies: 2
    Last Post: 03-14-2012, 10:54 PM
  3. Replies: 4
    Last Post: 01-26-2012, 12:55 AM
  4. Unresolved external on vector inside class constructor
    By Mario F. in forum C++ Programming
    Replies: 13
    Last Post: 06-20-2006, 12:44 PM
  5. std::vector resize and Class copy constructor
    By pianorain in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2005, 12:52 PM

Tags for this Thread