Skip to content

Instantly share code, notes, and snippets.

@kjelloh
Created August 18, 2016 20:21
Show Gist options
  • Save kjelloh/2599375abb008fae899de54d6a288f24 to your computer and use it in GitHub Desktop.
Save kjelloh/2599375abb008fae899de54d6a288f24 to your computer and use it in GitHub Desktop.
When C++ don't do what you expect. Or, Don't inherit from std::vector?

C++ don't always do what you think it should do?

"So you are brave enough to inherit from std::vector?" Paul looks curiously at me and I can't tell if he is joking or not. I had just told him about this program and how it does not work.

Quiz: Why does this program output a strange number of zeroes?

//
//  main.cpp
//  ibi
//
//  Created by Kjell-Olov Högdahl on 18/08/16.
//  Copyright © 2016 Kjell-Olov Högdahl. All rights reserved.
//

#include <vector>
#include <iostream>

namespace ibi {
    
    template <typename T>
    class Path : public std::vector<T> {
    public:
        Path() = default;
        Path(const Path& other) = default;
        Path(T vars...) : std::vector<T>(vars) {}
    };
    
}

int main(int argc, const char * argv[]) {
    {
        ibi::Path<int> path{17,23,15,74};
        std::cout << "\nibi::Path<int> path{17,23,15,74};";
        for (auto n : path) {
            std::cout << "\n\t" << n;
        }
    }
    {
        ibi::Path<int> path = {11,33,0,103};
        std::cout << "\nibi::Path<int> path = {11,33,0,103};";
        for (auto n : path) {
            std::cout << "\n\t" << n;
        }
    }
    
    return 0;
}

The output from this program is this.

ibi::Path<int> path{17,23,15,74};
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
ibi::Path<int> path = {11,33,0,103};
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
	0
@pauldreik
Copy link

I believe the Path(T) constructor is not variadic template, it is a c variadic parameter list. See here: http://en.cppreference.com/w/cpp/language/variadic_arguments
What happens is that the vars becomes 17, and the rest of the arguments are ignored. This calls the vector( size_type count ) constructor, which creates a vector with 17 elements, which become zero.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment