0 Replies - 817 Views - Last Post: 21 August 2009 - 07:51 PM Rate Topic: -----

#1 trikker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 03-August 09

Smart Pointer - container (vector) issue with template

Posted 21 August 2009 - 07:51 PM

I'm having some problems getting a vector to hold my smart pointer class counted_ptr.

Here is the code.

#include "std_lib_facilities.h"

template <class T>
class counted_ptr{
private:
	T* pointer;
	int* count;

public:
	counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {}	// default constructor
	explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
	~counted_ptr()
	{
		--*count;
		if(!*count) {
			delete pointer;
			delete count;
		}
	}

	counted_ptr& operator=(const counted_ptr& p)	// copy assignment
	{
		pointer = p.pointer;
		count = p.count;
		++*count;
		return *this;
	}
	T* operator->() const{ return pointer; }
	T& operator*() const { return *pointer; }
	int& operator[](int index) { return pointer[index]; }

	int Get_count() const { return *count; }	// public accessor for count


};




int main()
{
	counted_ptr<double>one;
	counted_ptr<double>two(one);
	one = new double(5);
	vector<counted_ptr> test;
	test.push_back(one);
}






The compiler gives an error when I try to create a vector<counted_ptr> giving the following errors.

C:\Users\Alex\C++\counted_ptr.cpp||In function `int main()':|
C:\Users\Alex\C++\counted_ptr.cpp|45|error: type/value mismatch at argument 1 in template parameter list for `template<class T> struct Vector'|
C:\Users\Alex\C++\counted_ptr.cpp|45|error: expected a type, got `counted_ptr'|
C:\Users\Alex\C++\counted_ptr.cpp|45|error: invalid type in declaration before ';' token|
C:\Users\Alex\C++\counted_ptr.cpp|46|error: request for member `push_back' in `test', which is of non-class type `int'|
||=== Build finished: 4 errors, 0 warnings ===|

I tried a few other things like using counted_ptr<T>, etc., but that would mean that vector has to know what T is and I can't parameterize vector. Any help is appreciated, thanks.

P.S. The smart pointer holds a generic pointer and an int pointer to count how many pointers are pointing to an object.

Edit: vector<counted_ptr<double> >test; compiles, but I can't use push_back on the counted_pointer. It gives a compiler error that opens up vector.tcc

This post has been edited by trikker: 21 August 2009 - 08:23 PM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1