473,715 Members | 6,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector<const T(*)> vs. vector<T(*)>

Hi all,

I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.
#include <vector>

int main(int arc, char** argv)
{
std::vector<con st intvec;
const int i = 5;
vec.push_back(i );
vec[0] = 4; //const has gone away

std::vector<con st int*pvec;
const int* pi = new int(5);
pvec.push_back( pi);
*(pvec[0]) = 4; // not possible because const, compile error

return 0;
}

From the first impression, it is not possible to create a vector of
const ints.
But you can do it with pointers.
Oct 30 '08 #1
12 5680
On 30 okt, 12:04, eiji.anonrem... @googlemail.com wrote:
Hi all,

I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.

#include <vector>

int main(int arc, char** argv)
{
std::vector<con st intvec;
const int i = 5;
vec.push_back(i );
vec[0] = 4; //const has gone away

std::vector<con st int*pvec;
const int* pi = new int(5);
pvec.push_back( pi);
*(pvec[0]) = 4; // not possible because const, compile error

return 0;

}

From the first impression, it is not possible to create a vector of
const ints.
But you can do it with pointers.
When you take whatever you put into the vector, you get a copy of it.
That means that your copy is not const, no matter what you put in.

The pointers you put in are not const - the ints they point to are. A
const pointer to a changeable int looks like

int * const x;
Oct 30 '08 #2

When you take whatever you put into the vector, you get a copy of it.
That means that your copy is not const, no matter what you put in.
#include <vector>

template<class Tclass MyInt {

T var;

public:
MyInt(T i):var(i){}

T GetT() {return var;}
T& GetTRef() {return var;}
MyInt& operator=(const MyInt& t) {
if (this != &t)
{
var = t.GetT();
}
return *this;
}
};

int main(int arc, char** argv)
{

const int i = 5;
MyInt<const intmi(i);

//mi.GetTRef() = 4; // error, variable is const
int x = 5;
MyInt<intmx(x);
mx.GetTRef() = 4; // this works
return 0;
}

Is that really a justification? In that example you can instantiate
MyInt with "const int" and only "int". In both cases the value is
copied, but var is not "int" in both cases.
Oct 30 '08 #3
On Oct 30, 6:04*am, eiji.anonrem... @googlemail.com wrote:
Hi all,

I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.

#include <vector>

int main(int arc, char** argv)
{
* * * * std::vector<con st intvec;
* * * * const int i = 5;
* * * * vec.push_back(i );
* * * * vec[0] = 4; //const has gone away

* * * * std::vector<con st int*pvec;
* * * * const int* pi = new int(5);
* * * * pvec.push_back( pi);
* * * * *(pvec[0]) = 4; // not possible because const, compile error

* * * * return 0;

}

From the first impression, it is not possible to create a vector of
const ints.
But you can do it with pointers.
One of the requirements for elements in a container like
std::vector<>, is that those elements be assigneable and copyable. So
const int is a no-no but const int* is fine since that pointer can be
reseated.

Oct 30 '08 #4
Salt_Peter wrote:
One of the requirements for elements in a container like
std::vector<>, is that those elements be assigneable and copyable.
Do I remember wrongly that the next standard will introduce the means
to actually allow standard containers to have const elements (in other
words, you can add and remove elements from the container, but you can't
modify the values of existing ones)?
Oct 30 '08 #5
On Oct 30, 4:04*am, eiji.anonrem... @googlemail.com wrote:
Hi all,

I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.

#include <vector>

int main(int arc, char** argv)
{
* * * * std::vector<con st intvec;
* * * * const int i = 5;
* * * * vec.push_back(i );
* * * * vec[0] = 4; //const has gone away

* * * * std::vector<con st int*pvec;
* * * * const int* pi = new int(5);
* * * * pvec.push_back( pi);
* * * * *(pvec[0]) = 4; // not possible because const, compile error

* * * * return 0;

}

From the first impression, it is not possible to create a vector of
const ints.
But you can do it with pointers.
This is exactly the reason I always use const on the right (correct)
side, especially when dealing with pointers/references.
'const int' is simply a special case way to write: 'int const'. or
with pointers 'const int *' is 'int const *'
Remember: declarations are read right to left from the variable name.
With this in mind the problem is extremely clear:
int const * - poiter to a constant int (pointer can change, integer
cannot)
int * const - constant pointer to an int (integer can change, pointer
cannot)
Oct 30 '08 #6
On Oct 30, 12:25*pm, Juha Nieminen <nos...@thanks. invalidwrote:
Salt_Peter wrote:
One of the requirements for elements in a container like
std::vector<>, is that those elements be assigneable and copyable.

* Do I remember wrongly that the next standard will introduce the means
to actually allow standard containers to have const elements (in other
words, you can add and remove elements from the container, but you can't
modify the values of existing ones)?
That seems dangerous. To remove an element would imply destruction,
which is non-const. You can still get const-only access to elements
via const_iterator or const&, or std::set essentially functions like
this.
Oct 30 '08 #7
On Oct 30, 12:04 pm, eiji.anonrem... @googlemail.com wrote:
I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.
#include <vector>
int main(int arc, char** argv)
{
std::vector<con st intvec;
This is illegal---undefined behavior according to the standard.
It doesn't compile with my compiler (g++, with the usual
options). And whatever happens if it does compile, you can't
count on it.
const int i = 5;
vec.push_back(i );
vec[0] = 4; //const has gone away
Maybe. Or maybe it core dumps. Or maybe just about anything
else. (I would generally expect it not to compile, but the
standard doesn't require an error message.
std::vector<con st int*pvec;
const int* pi = new int(5);
pvec.push_back( pi);
*(pvec[0]) = 4; // not possible because const, compile error
return 0;
}
From the first impression, it is not possible to create a
vector of const ints. But you can do it with pointers.
What's in the vector cannot be const. You can create a vector
of non-const pointers to const (which is what you did), but not
of const pointers to anything. (You're probably being confused
by a widespread abuse of language. int const* is not a const
pointer, but a pointer to const. A const pointer would be int*
const or int const* const. More generally, just remember that
the const applies to whatever precedes it.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 31 '08 #8
Thank you all.

I guess my initial post was somewhat missleading.
I only wanted to say that, when you want to have a vector of const
objects, you have to use pointers!

The "assignable & copyable" rule is the point.
"const T" would be copyable, but not assignable.

I thought it should be possible to allow the creation of a vector of
"const T" because at creation there is no need for an assignment. Or
am I missing something?

Oct 31 '08 #9
xdotx wrote:
That seems dangerous. To remove an element would imply destruction,
which is non-const.
Incorrect.

void deleteFoo(const Foo* const foo)
{
delete foo; // Compiles and works just fine.
}
You can still get const-only access to elements
via const_iterator or const&, or std::set essentially functions like
this.
Even if you *can* get const access with the current system, that
doesn't mean it wouldn't be nice if there was a way to *ensure* that the
values of the elements are never modified by accident.
Oct 31 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4872
by: Joseph Turian | last post by:
Some function requires a vector<const foo*> argument. How can I cast a vector<foo*> to vector<const foo*>? Thanks! Joseph
4
2787
by: hn.ft.pris | last post by:
Hi: I've got the following simple code to test vector<const T>, #include <vector> #include <iostream> using namespace std; int main( void ){ vector<const intvec;
1
4905
by: Shafik | last post by:
Hello folks, Whats the reason for the STL not allowing this: vector<const stringv = vector<const string>(); --Shafik
9
2244
by: t | last post by:
Can you use a plain iterator to vector<const intto write to it? It doesn't seem like it should be possible, but Visual C++ 2005 Express lets me: vector<const intvc; vc.push_back(5); vector<const int>::iterator iter = vc.begin(); *iter = 3; // compiles
6
3430
by: muzicmakr | last post by:
I'm porting some code from windows to mac, and there are some instances of std::vector<const MyType>, that compiled just fine on the pc, but won't compile under gcc. I'd never tried to do this particular construct myself, and after some searching online, I found a post somewhere saying this isn't legal c++ because the standard containers need types that are assignable. My questions-- is that correct? Why does visual studio allow it if...
0
8821
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9340
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9103
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3175
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2118
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.