当我这样做:
std::vector<int> hello;
Run Code Online (Sandbox Code Playgroud)
一切都很好.但是,当我把它作为引用的向量时:
std::vector<int &> hello;
Run Code Online (Sandbox Code Playgroud)
我得到了可怕的错误
错误C2528:'指针':指向引用的指针是非法的
我想把一堆结构的引用放到一个向量中,这样我就不必插入指针了.为什么矢量会对此发脾气?我唯一的选择是使用指针向量吗?
我遇到了这个问题,维护一个大的端口(相对于我们团队的大小)项目,但是创建一个小例子很简单.stackoverflow.cpp:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main (int argc, char *argv[]) {
stack<const string> strstack;
string str("Hello, world");
strstack.push(str);
cout << strstack.top() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
看起来没错,对吧?MSVS也这么认为.然而:
g++ stackoverflow.cpp
In file included from /usr/include/c++/4.7/x86_64-linux-gnu/bits/c++allocator.h:34:0,
from /usr/include/c++/4.7/bits/allocator.h:48,
from /usr/include/c++/4.7/string:43,
from /usr/include/c++/4.7/bits/locale_classes.h:42,
from /usr/include/c++/4.7/bits/ios_base.h:43,
from /usr/include/c++/4.7/ios:43,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from stackoverflow.cpp:1:
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const std::basic_string<char> >’:
/usr/include/c++/4.7/bits/allocator.h:89:11: required from ‘class std::allocator<const std::basic_string<char> >’
/usr/include/c++/4.7/bits/stl_deque.h:489:61: required from ‘class std::_Deque_base<const std::basic_string<char>, std::allocator<const std::basic_string<char> > >’
/usr/include/c++/4.7/bits/stl_deque.h:728:11: required …Run Code Online (Sandbox Code Playgroud)