Can't work with volatile objects?

F

Frederick Gotham

The canonical way to write a copy-constructor is:

MyClass::MyClass(MyClass const&);

I've been wondering, however, if that should be:

MyClass::MyClass(MyClass const volatile&);
?

Just in case more type specifiers come into the language, we could have a
template such as the following:

template<class Param>
class Strict {
private:
Strict(); /* Can't create an object */

public:

typedef Param const volatile T;
};

, and then have function arguments such as:

MyClass::MyClass(Strict<MyClass>::T &)
{

}

The following code demonstrates how volatile objects aren't catered for:

#include <cstddef>
#include <algorithm>

using std::size_t;
using std::copy;

class MyClass {
private:

typedef int T;

size_t const static len = 10;

T *p;

public:

MyClass() : p(new T[len]) {}

MyClass(MyClass const &from) : p(new T[len])
{
copy(from.p,from.p + len,p);
}

MyClass &operator=(MyClass const &from)
{
copy(from.p,from.p + len,p);
return *this;
}

~MyClass()
{
delete [] p;
}
};

int main()
{
MyClass const volatile obj1;

MyClass obj2(obj1); /* Can't copy */
}


(I just used copy-constructors as an example -- it could be any function:

void Func(MyClass const &);
 
M

Michiel.Salters

Frederick said:
The canonical way to write a copy-constructor is:

MyClass::MyClass(MyClass const&);

I've been wondering, however, if that should be:

MyClass::MyClass(MyClass const volatile&);

No. That would force the implementation to use volatile sematics even
if
the copied object isn't volatile. Forcing const sematics usually has no
performance overhead, so there is little reason to overload the copy
ctor
with a non-const overload. If you need volatile, add it as an overload,
but
keep the efficient non-volatile one.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top