Goldman Sachs Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
1
of 1 vote

template<typename T> class SmartPointer {

public:
	SmartPointer(const SmartPointer& other){
		this->operator=(other);
	}

	SmartPointer(): ptr (0), refCount(new int(1)) {}

	explicit SmartPointer(T* newPtr): ptr (newPtr), refCount( new int(1) ) {}

	SmartPointer& operator=( const SmartPointer& smartPtr ){
		if( this != &smartPtr ){
			ptr = smartPtr.ptr;
			refCount = smartPtr.refCount;
			incRefCount();
		}
		return *this;
	}

	virtual ~SmartPointer(){
		decRefCount();

		if( ptr && ! *refCount ){
			delete ptr;
			delete refCount;
			cout << "ptr deleted"<< endl;
			ptr = 0;
		}
	}

	T* operator->() const {
		return ptr;
	}

	T& operator*(){
		return *ptr;
	}

	int getRefCount() const {
		return *refCount;
	}

private:
	T* ptr;
	int* refCount;


	void incRefCount(){
		++(*refCount);
	}

	void decRefCount(){
		--(*refCount);
	}
};

- m@}{ April 18, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

gud one... :)

- dollcy July 18, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I have a question about this, which I've also noticed in other smart-pointer implementation examples.

I guess I don't understand the usage, because it seems this code, in the assignment operator implementation:

ptr = smartPtr.ptr;
			refCount = smartPtr.refCount;

inadvertently leak ptr and refCount in the lhs instance if it's already set up before the assignment?

- dlanznar September 07, 2011 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More