-4

Are there any advantages of it, or its bad idea? Why its bad?

std::vector<object> * vec;

I found similar question, but it did not explain why should we use/not use it, thats why Im asking.

C++ Any benifits using pointer to vector of pointers?

Only reason that I know there are:

Pointer may be null

std::vector<object> * vec == nullptr;
if (vec == nullptr) vec = new std::vector<object>(size);

size is 8

of pointer on stack is 8, and vector has 3 pointers on stack so 24

Any other reasons?

yourstruly
  • 972
  • 1
  • 9
  • 17
  • The answer should be the same as this https://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself?rq=1, I can't think of any reasons it'd differ for `vector` – Tas Jul 23 '18 at 00:27
  • In what specific situation? – Galik Jul 23 '18 at 00:27
  • 2
    There might be a reason for using such a thing - there is often a reason for using just about any type in very specialised circumstances. You don't want to be actively looking for those circumstances, though. You will know them when you come across them. I can't say I've ever used a pointer to vector in any of my own code. –  Jul 23 '18 at 00:27

1 Answers1

0

Only in very rare circumstances. For example, I may have a function like this:

int foo(const Foo& x, std::vector<int>* y);

Given Foo, it calculates some integer value and returns it. If y is not NULL, it also stores something else to y.

Don't use pointer to vector, unless you are really sure you need it.

user31264
  • 6,557
  • 3
  • 26
  • 40
  • Then maybe tell why use reference? If u ask him, who shall he ask? – yourstruly Jul 23 '18 at 00:42
  • Presumably the "if `y` is not NULL" part is the reason for a pointer parameter rather than reference. But note you can't usefully "store something else to `y`", because `*y` is `const` and `y` itself is local. – aschepler Jul 23 '18 at 00:49
  • hmm we have here variable y pointing to const vector? then vector that had been pointed to can be changed, but it will still be same memory address of poiner? or is it opposite? – yourstruly Jul 23 '18 at 00:57
  • @NeilButterworth because there is no such thing as NULL reference. – user31264 Jul 23 '18 at 01:15
  • @yourstruly - removed const. – user31264 Jul 23 '18 at 01:17
  • To improve this answer, you could contrast `int*`, `vector*`, `foo*` and `interface*`; and point out that none are commonly actually needed much. But answer is fine as is. – Yakk - Adam Nevraumont Jul 23 '18 at 03:53