2

I wrote a File class in File.h. And I wrote Directory class in Directory.h which is include File& vector. Two header has same namespace.

Here is the code:

#include "File.h" #include <vector> class Directory : public File { public: ... private: std::vector<(File&)> files; }; 

When I try to compile it, it says:

In file included from Directory.cpp:1:0: Directory.h:29:30: error: template argument 1 is invalid std::vector<(File&)> files; ^ Directory.h:29:30: error: template argument 2 is invalid 
7
  • 3
    You cannot have std::vector of reference types. The type must be copyable. Any reason why not to use std::vector<File>? Commented Dec 19, 2015 at 11:53
  • Then I should use pointers? Thank you. Commented Dec 19, 2015 at 11:55
  • And you need them for? Polymorphism? Commented Dec 19, 2015 at 11:56
  • 3
    No, it won't work. the best is to have vector of smart pointers. Commented Dec 19, 2015 at 12:00
  • 1
    You missed LogicStuff's point. Although there is a relationship, a smart pointer is distinct from a pointer. Commented Dec 19, 2015 at 12:40

1 Answer 1

8

To clear things up for you, std::vector requires its elements to be CopyAssignable, which references aren't.

std::vector<File&> is a vector of references to File, note that std::vector<(File&)> is a syntax error.

You thought std::vector<File> & would work, but no. It's a reference to a vector of what? Objects. Polymorphism won't work there. And you'd need an actual std::vector<File> instance to refer to.

You need a vector of pointers, which can be copy-assigned.

If you go with raw pointers, you'll need not to forget delete before you remove any element, or you'll leak memory (if an object was allocated on heap, of course). Smart pointers will do that for you:

std::vector<std::shared_ptr<File>> files; // or std::vector<std::unique_ptr<File>> files; 

Reference: std::shared_ptr, std::unique_ptr.

Sign up to request clarification or add additional context in comments.

Comments